$ vue --version
If you have not installed it yet, type the command given below to install Vue.js globally on your Operating system:
$ npm install -g @vue/cli
After successfully installing Vue.js globally on your Operating system, create the Vue project by typing the “vue create” command given below, followed by the project name:
$ vue create vue-project-name
It will ask you to either select the preset or select your own custom preset for the Vue project.
After configuring or selecting the default preset, the Vue project will be created in a while.
After creating the Vue project, navigate to the newly created project’s directory using the “cd” command.
$ cd vueprojectname
At this stage, you have successfully set up the Vue project.
Install Bootstrap
Once your system is ready, and the Vue project is set up! You can install the “bootstrap-vue” using the Yarn or NPM.
If you want to install the simple “bootstrap” for styling purposes, you can type the command given below to install them.
For installing ‘bootstrap-vue’ and ‘bootstrap’ using the Yarn package manager, type the command given below:
$ yarn add bootstrap bootstrap-vue
OR
For installing ‘bootstrap-vue’ and ‘bootstrap’ using the NPM package manager, type the command given below:
$ npm install bootstrap bootstrap-vue --save
Alright! Once the ‘bootstrap’ and ‘bootstrap-vue’ are installed, You have to enable them in the main.js file.
import BootstrapVue from 'bootstrap-vue/dist/bootstrap-vue.esm';
import 'bootstrap-vue/dist/bootstrap-vue.css';
import 'bootstrap/dist/css/bootstrap.css';
Vue.use(BootstrapVue);
After enabling the “bootstrap” and “bootstrap-vue”, you can now use them in your Vue project.
How to Use Bootstrap in Vue
To use Bootstrap with Vue, ‘bootstrap-vue’ provides various components to use as a Vue component.
For example, a button can be created using the ‘bootstrap-vue’ like this.
<b-button variant="success">Button</b-button>
For knowing about further components, feel free to visit the official documentation page of BootstrapVue.
This is how simple it is to install and start using bootstrap in a Vue project.
Conclusion
Bootstrap is a prevalent CSS front-end library used for building mobile-first and responsive web apps, and with the help of BootstrapVue, we can build such web applications using Vue.
In this post, we walk through the installation of BootstrapVue in a Vue.js project and also see how to enable it and use it.
With the combination of such two robust libraries, we can speed up the development process and beautify our web application to the highest limits.
Vue Watch to make Dynamic Interaction
Vue.js is a very impressive and reactive JavaScript’s front-end framework used to develop front-end websites quickly and easily.
This post will learn about the watch property that is one of the most fundamental concepts.
Vue.js provides a watch property to watch a variable, and on the change of that variable, it allows us to run a function so that we can make Dynamic Interaction.
Let’s try an example and have some dynamic interaction using the Vue Watch property.
Example
We will first try to change some variable at the click of a button, and then using the watch property, we will watch that variable and alter some other variable to make the dynamic changes on the web page.
First, assume we have two variables.data() {
return {
buttonBool: true,
color: "red"
}}
And we have bound the “buttonBool” variable with a button element in the template.
<template>
<div class="test">
<h1>This is a testing page</h1>
<button @click="buttonBool=!buttonBool">Click me!</button>
</div></template>
We want to change the background color of a, let’s say, a division at the click of the button.
So, first, create a div in the template.
<template>
<div class="test">
<h1>This is a testing page</h1>
<button @click="buttonBool=!buttonBool">Click me!</button>
<div></div>
</div></template>
Now, let’s first create a watch property and change the state of the “color” variable at the change of the “buttonBool” variable.
watch:{
buttonBool(){
this.color = !this.color;
}}
Alright! The last step left is to change the classes of the div on the change of color variable.
So, let’s do that by using the class binding feature of Vue.js.
<template>
<div class="test">
<h1>This is a testing page</h1>
<button @click="buttonBool=!buttonBool">Click me!</button>
<div :class="[color ? 'red' : 'green', 'box']"></div></div></template>
Here, I have just assigned the class “red” if the state of the “color” variable is true, else “green” if the state of the color variable is “false,” and the “box” class is assigned in any case.
The CSS for giving the width, height, and background color to the div is as follows.
<style scoped>
.box{
width: 100px;
height: 100px;
margin: 15px auto;}
.red{
background-color: red;}
.green{
background-color: green;}
</style>
Alright, after getting done with the coding stuff, my web page would be like this.
Now, whenever I click the button, the background color of the box should get changed.
And you can witness in the gif above, the color of the div is changing at the click of the button.
That’s amazing, right!
So, this is how we can use the Vue Watch to make dynamic interaction on the webpage.
Conclusion
In this post, we have tried to change some variable’s state at the click or change of some other variable using the watch property of Vue.js.
We have also made some dynamic changes to the web page.
We have seen that at the click of the button, in the on-click attribute, we changed the variable’s state and shown that the watch property watched the variable and performed some action like changing some other variable’s state.
What is a Vue Directive, and how to use it?
A framework aims to provide such features that make the development process easier and faster for the developers.
Vue.js is such a feature-enriched JavaScript framework that provides many built-in functions and directives to quickly make the development process.
But, there must come some scenarios when you need some functionality that is not available by the framework, so you have to build your own.
In this post, we will learn and take a look at the built-in directives provided by the Vue.js framework, and we will also learn to create and use our own custom-made Vue directive.
Directive
Directives are attributes that you can link with the DOM elements, prefixed by the clause “v-” which helps to know the library that it is a special type of syntax used for performing some tasks.
Directives are usually used for direct manipulation of DOM.
Some of the most used and famous directives are “v-if”, “v-for”, and “v-show”.
The directives are used to apply effects on DOM elements but reactively.
Let’s understand it with an example:
“v-if” Directive
<p v-if= "showText"> You can view the text.</p>
In the above tag, the “v-if” is a directive that will delete or add the paragraph tag “<p>”, depends on the “showText” variable’s truthiness.
“v-show” Directive
Similarly, we have the “v-show” directive which can perform the same functionality described above:
<p v-show= "showText"> You can view the text.</p>
The subtle difference between “v-if” and “v-show” is that “v-if” does not render the element while loading the page if the bound variable is not true and it loads when the variable becomes true.
In contrast, “v-show” will render the element at the web page’s load time but hides it.
So, “v-if” is time effective at the page’s load time and time-consuming when the variable gets true.
It has to render the whole element while “v-show” is time effective upon the truthiness of the variable time-consuming at the load time of the web page.
Alright! Let’s have a look at a directive that takes the argument.
“v-bind” Directive
Another most widely used directive is “v-bind,” which is used for interacting and updating the HTML attributes.
For example, if we want to bind some variable to the “href” attribute of the <a> tag, we can bind the “href” attribute like this:
<a v-bind:href="url"></a>
“v-on” Directive
Just like the “v-bind” directive, Vue provides a “v-on” directive for binding the variable for listening to the events fired in the DOM.
For example, for listening to the Click event and binding some variable to it, the syntax would go like this:
<button v-on:click="buttonBool=!buttonBool">Click me!</button>
In the inverted commas, we can provide the expression as well as functions.
Conclusion
We have learned about the directives in Vue and see how to use the directives in Vue.js.
We have discussed some of the most used and basic built-in directives of Vue.js, which helps a lot and saves a huge amount of time in the development.
Vue Computed Deep Structures
When it comes to the computation of nested or deep data types like arrays or objects, Vue.js or any other programming language does not automatically detect the hierarchical change in the data.
However, we all know that Vue.js provides the watch and computed properties to perform some change variables.
But when it comes to nested data changes, Vue.js does not detect that.
This post will learn to perform some changes by watching the nested data of arrays or objects.
Before learning about watching nested data in Vue.js, let’s first understand how the watch property works?
Watch Property
The watch property is used to watch a variable and allows the user to perform some desired tasks on the variable’s change.
Example: Watch a Variable
For example, at the change of some variable, we want to console something.
The syntax for writing such code in Vue will go like this:
<template>
<div class="test">
<h1>This is a testing page</h1>
<button @click="boolVar=!boolVar">Click</button>
</div></template><script>
export default {
name: "Test",
data(){
return{
boolVar: true
}
},
watch:{
boolVar(){
console.log("Button clicked.")
}
}};</script>
After writing the above code, the web page would be like this.
If we click on the button, the state of the “boolVar” should be altered due to the button’s on-click attribute, and the watch should automatically detect the change in “boolVar” and display the message string on the console.
It worked perfectly fine; the message “Button clicked” is displayed on the console.
But, the watcher fails to detect the change and does not get fired when it comes to watching the arrays or objects.
Let’s see a demonstration of that.
Example: Watching an Object
Suppose we have an object in our component, and we want to display the change that happened in the object’s property.
In the example given below, I have created an object with the name of “objVar,” which contains two key-value pairs, “item” and “quantity”.
I have created a button where I am adding “1” to the template tag’s quantity.
Lastly, I am watching the “objVar” object in the watch property and displaying a console message.
<template>
<div class="test">
<h1>This is a testing page</h1>
<button @click="objVar.quantity=objVar.quantity+1">Click</button>
</div></template><script>
export default {
name: "Test",
data(){
return{
objVar: {
item: "Item1",
quantity: 1
}
}
},
watch:{
objVar(){
console.log("Button clicked & Quantity = " + this.objVar.quantity)
}
}};</script>
Now, this code is supposed to display the change in the quantity of the object.
But, when we execute the code and click the button on the web page:
You can see in the above gif; nothing is happening in the console.
The reason behind this is that the watcher does not look deep into the values of the objects, and this is the real problem to which we are going to solve now.
Vue.js provides the deep property for watching deep down into the values of objects and arrays.
The syntax for using the deep property and watching the nested data is as follows:
<script>
export default {
name: "Test",
data(){
return{
objVar: {
item: "Item1",
quantity: 1
}
}
},
watch:{
objVar: {
deep: true,
handler(){
console.log("Button clicked & Quantity = " + this.objVar.quantity)
}
}
}};</script>
In this syntax, we have set the deep property to true and rearranged the handler() function.
Now, after changing the code, if we reload the web page and click on the button:
Here you can see that the watcher is working and displaying the message in the console.
Conclusion
After reading this post, watching and computing deep or nested data structures in Vue.js is not difficult anymore.
We have learned how to watch the change of a value in an object or array and execute some tasks with the help of the “deep” property of Vue.js.
Vue Computed Property not updating; Troubleshooting Steps
Vue.js is a very popular JavaScript library that is known for its reactivity, flexibility, and intuitive API.
However, reactivity and flexibility come with some drawbacks, leading to the developer’s performance or a headache.
The computed property is a very famous and most known feature of Vue.js, which is used to update some variable or perform some calculation depending upon some other variable’s updation.
This post will try to troubleshoot the problems that occurred when the computed property does not work or update what we want.
Let’s have a look at the scenarios, what might go wrong, and Vue Computed Property not updating.
Scenario # 1:
First of all, make sure you did not make any logical error like implementing the wrong logic.
To avoid the possible logical errors, check the following things:
Verify that variable names are correct.
You are taking care of the scopes of the variable using “this”.
Scenario # 2:
The second thing you might have mistaken in the computed property is that you are not caring about the Computed property’s side effects like editing some data inside a computed property or calling other functions.
For example, reversing the array within a computed property.
Suppose we have an array in our component.
data(){
return{
arrVar:[1,2,3]
}
},
In the computed property, we are reversing the array.
computed:{
arrayReverse(){
return this.arrVar.reverse();
}
}
But, when we run the project, it will show an error of ‘Unexpected side effect in “arrayReverse” computed property.’ because it will always do the same task again and again and reverse the original array every time.
So, try to avoid data manipulation in the computed property, and it will work perfectly fine for you.
Scenario # 3:
Another scenario could be that the computed property is stuck in an infinite loop, and it keeps on re-computing something.
Since computed property watches every variable included in the computed property and reacts or gets recomputed on the change of any variable involved in this property, if you change the state of any variable inside the computed property, the computed property detects the change.
It starts to re-compute itself, and it won’t be able to get out of this infinite loop.
These are some of the possible ways which could lead to the computed property not updating problem.
Conclusion
This post has gone through the most common scenarios the developers faced for Vue Computed property not updating and provided profound and to-the-point troubleshooting steps for each scenario.
If you still have not found your solution yet, feel free to ask your questions on the Vue community platforms and get your questions answered within no time.
Vue Computed with Parameter
The Computed property is usually used to compute data from some other data.
It is known for its reactivity because whenever a variable involved in some computed property gets changed, the whole property gets recomputed.This post will learn to pass the parameter to computed property and see how to use Vue computed with parameter.
Before getting started with passing parameters to the computed property, let’s first understand the computed properties by going through the example.
Examples
Suppose we have two variables named “firstName” and “lastName” in our Vue component:
//..
data(){
return{
firstName: "",
lastName: ""
}
},//..
Computed Property
We want to compute a “fullName” property that will combine the “firstName” and “lastName” and recompute the fullName whenever any of the two variables “firstName” and “lastName” gets changed.
So, the computed property for computing the full name would be like this:
//..
computed:{
fullName(){
return this.firstName + ' ' + this.lastName;
}
}//..
Now let’s create some input fields and bind the “firstName” and “lastName” variables to the input fields and also bind the “fullName” property in the ‘p’ tag to view the instant change on the change of the first anime of the last name.
The HTML part of this component will be like this:
Alright! After having all this setup, let’s take a look at our webpage.
If you have successfully written the correct code and run it, you should also have the two input fields on your web page.
Let’s try to type the first name and last name and see either the “fulName” property gets computed or not.
Here in the screenshot given above, you can witness the marvelous reactivity of Vue.js using the computed property.
You can also witness that it is not like watching a single variable and changing some other variable’s value.
Still, it is watching each variable included in the computed property and re-computing the “lastName”.
Let’s see how we can pass parameters to the computed property and use it.
Pass parameters to the Computed Property
For passing the parameters to the computed property, we just pass the parameters as we do for the function.
For example, in the template, when we have bound the variable “lastName,” we want to pass some string, so the template part of our component would be like this:
Now, in the computed property, the passed parameter can be utilized using the following syntax.
computed:{
fullName(){
return message1 => {
return `${message} ${this.firstName} ${this.lastName}`
}
}
}
This is how we can pass a parameter to the computed and get it in the property and use it.
If we again look at our web page and type the First name and last name, you can have the same functionality and reactivity, but this time, the parameter passed.
This is how simple and easy it is to pass a computed property parameter and use it.
Conclusion:
The computed property is a very powerful feature of Vue.js, and we have learned that it comes in handy when we have to change them when their dependencies get changed.
We have learned to pass the parameter and use it in the computed property.
How to Build A Simple Blog With Hexo Static Site Generator
In the modern age, websites are the building blocks of information.
From enterprise, eCommerce, social websites to simple blogs, websites allow people to share ideas and thoughts.
This tutorial will show you how you can set up a simple blog using a static site generator that is very fast and easy to use.
What Is An SSG?
SSG, or Static Site Generator, is a web application that converts the dynamic content on a webpage into static content usually stored locally.
Static site generators do not require databases and backends, thereby eliminating the need to learn how to code.
It mainly focuses on writing and presenting the content.
SSG vs.
CMS
The most popular way to create websites and manage content is using CMS or Content management systems such as WordPress, Drupal, Joomla, etc.
CMS systems work by creating and managing content directly using an interactive interface.
Since data in a CMS is retrieved from the database, CMSs are very slow as the content is fetched and served as dynamic content.
CMS systems are also prone to security vulnerabilities as they rely on external plugins written by other developers to increase functionality.
On the other hand, static site generators work by creating content offline mediums such as text editors and renders the final page view upon publication.
Since the content is locally-rendered, with no need for a database, the page renders faster, and load speeds are incredibly fast.
Static site generators are made of pre-compiled code that acts as an engine to render the published content.
How to Build a Static Blog With Hexo
One of the popular choices for building a static site is Hexo.
Hexo is a simple, fast, and powerful SSG application written in NodeJS.
Although there are other choices for building a static site, Hexo allows you to customize your site and integrate various tools.
Let us look at how we can set up a simple static site with Hexo.
Installing Hexo
Before we can build a site, we need to set up hexo requirements and install it.
For this, we require NodeJS and git.
Start by updating your system:
sudo apt-get updatesudo apt-get upgrade
Once you have your system up to date, install git
sudo apt-get install git
Next, install nodejs from nodesource using the command:
curl -sL https://deb.nodesource.com/setup_14.x | sudo -E bash -apt-get install -y nodejs
Once you have Nodejs installed, we can proceed to install hexo using the command:
npm install -g hexo-cli
Working with Hexo
Once you have installed hexo, you can create a site and publish content.
Let us look at how to work with Hexo.
Keep in mind that this is a quick, simple guide.
Refer to the documentation to learn more.
Creating a site
To create a new hexo site, use the command below:
hexo init HexoSitecd HexoSite
npm install
Understanding Hexo Directory structure
Once you initialize a new Hexo site, you will get a directory structure such as the one below:
-rw-r--r-- 1 cs cs 0 Feb 8 20:51 _config.landscape.yml-rw-r--r-- 1 cs cs 2439 Feb 8 20:51 _config.yml drwxr-xr-x 1 cs cs 4096 Feb 8 20:51 node_modules-rw-r--r-- 1 cs cs 615 Feb 8 20:51 package.json-rw-r--r-- 1 cs cs 56716 Feb 8 20:51 package-lock.json drwxr-xr-x 1 cs cs 4096 Feb 8 20:51 scaffolds drwxr-xr-x 1 cs cs 4096 Feb 8 20:51 source drwxr-xr-x 1 cs cs 4096 Feb 8 20:51 themes
The first file is the _config.yml contains all the settings for your site.
Ensure to modify it before deploying your site because it will contain default values.
The next file is the package.json file that contains the NodeJS application data and configurations.
Here, you will find installed packages and their versions.
You can learn more about the package.json from the resource page below:
https://docs.npmjs.com/cli/v6/configuring-npm/package-json
Creating a Blog
To create a simple blog in hexo, use the command:
hexo new blog “Hello World Blog”
Once created, you can file the markdown file under /source/_posts directory.
You will need to use Markdown markup language to write content.
Creating a new page
Creating a page in Hexo is simple; use the command:
hexo new page “Page-2”
The page source is located under /source/Page-2/index.md
Generating and Serving content
Once you publish your content on hexo, you will need to run the application to generate the static content.
Use the commands below:
$ hexo generate
INFO Validating config
INFO Start processing
INFO Files loaded in 966 ms
INFO Generated: archives/index.html
INFO Generated: Page-2/index.html
INFO Generated: archives/2021/index.html
INFO Generated: index.html
INFO Generated: archives/2021/02/index.html
INFO Generated: js/script.js
INFO Generated: fancybox/jquery.fancybox.min.css
INFO Generated: 2021/02/08/Hello-World-Post/index.html
INFO Generated: css/style.css
INFO Generated: 2021/02/08/hello-world/index.html
INFO Generated: css/fonts/FontAwesome.otf
INFO Generated: css/fonts/fontawesome-webfont.woff
INFO Generated: css/fonts/fontawesome-webfont.eot
INFO Generated: fancybox/jquery.fancybox.min.js
INFO Generated: css/fonts/fontawesome-webfont.woff2
INFO Generated: js/jquery-3.4.1.min.js
INFO Generated: css/fonts/fontawesome-webfont.ttf
INFO Generated: css/images/banner.jpg
INFO Generated: css/fonts/fontawesome-webfont.svg
INFO 19 files generated in 2.08 s
To serve the application, run the command:
$ hexo server INFO Validating config INFO Start processing INFO Hexo is running at http://localhost:4000 .
Press Ctrl+C to stop.
Conclusion
This quick and simple introduction has shown you how to use the Hexo static site.
If you need more information on how to work with Hexo, please refer to the main documentation provided below:
https://hexo.io/docs
How to Authorize Users Using Google OAuth in Node.js
Open Authorization, also known as OAuth, is a protocol used to authorize a user on your website using some third-party service like Google, Github, Facebook, etc.
The third-party service shares some data (name, email, profile picture, etc.) with your website and then authorizes the user on its behalf without managing the passwords and usernames for your website, and saving the users a lot of extra trouble.
How OAuth Works
When a user clicks on “Login with Google”, it takes the user to the Google OAuth consent page.
When the user agrees to the consent and authenticates his identity on Google, Google will contact your website as a third party service and authorize the user on its behalf and share some data with your website.
In this way, the user can be authorized without managing the credentials for your website separately.
Implementing Google OAuth using Node.js
Almost all the programming languages provide different libraries to implement google oauth to authorize users.
Node.js provides ‘passport’ and ‘passport-google-oauth20’ libraries to implement google oauth.
In this article, we will implement an oauth protocol to authorize users to use node.js.
Create a Project on Google
The first step to implement Google OAuth is to create a project on the google developer console for your website.
This project is used to get the API keys used to make requests to Google for open authentication.
Goto the following link and create your project:
https://console.developers.google.com
.
Configuring Google Project
After you create the project, go into the project and select “OAuth consent screen” from the left side menu.
Click on the ‘create’ button and provide all the details of your project.
Click “Save and Continue” to move on.
Now provide the scope of your project.
Scopes are the types of permissions to access the user’s data from a google account.
You need to set up the permissions to get specific user data from your google account.
Click “Save and Continue.”
Now add the test users to the project if you want.
Test users are the only allowed users who can access your web application in Testing mode.
For now, we will not enter any test user and click “Save and Continue” to move on to the summary page of the project.
Review your project on the summary page and save the configuration.
Now we will generate credentials for our project.
Select the ‘Credentials’ tab on the left side menu and click on the ‘Create credentials’ button on top to generate OAuth 2.0 Client IDs.
From the dropdown menu, select ‘OAuth client ID’ and specify the type of application as ‘Web application’ and your application’s name.
On the same page, we have to provide two URIs, the ‘Authorized Javascript Origins’ and the ‘Authorized redirect URIs’.
The ‘Authorized javascript origins’ is the HTTP origin of your web application, and it can not have any path.
The ‘Authorized redirect URIs’ is the exact URI with a path where the user will be redirected after google authentication.
After entering all the required entries, click on ‘create’ to create OAuth credentials.
Initiating Node.js Project
So far, we have created a google project to authorize users for our application using google.
Now we are going to initiate the node.js project to implement oauth.
Create a directory named ‘auth’ and initiate the express project.
ubuntu@ubuntu:~$ mkdir authubuntu@ubuntu:~$ cd authubuntu@ubuntu:~$ npm init -y
Installing Required npm Packages
To implement Google OAuth using node.js, we need to install some npm packages.
We will use ‘passport’, ‘express’, ‘path’, and ‘passport-google-oauth20’.
Install these packages using npm.
ubuntu@ubuntu:~$ npm install express passport passport-google-oauth20 path
Writing Node.js Code
First of all, we will write two simple html web pages, the one with a button, and authorize the user when clicked on the button.
The second page will be authorized, and the user will be redirected to the authorized page after authorization.
Create a file ‘public/index.html’.
<html>
<head>
<title>OAuth</title>
</head>
<body>
<a href=”/google/auth”>Authorize Here</a>
</body></html>
Now create a file ‘public/success.html’ with the following content.
<html>
<head>
<title>OAuth</title>
</head>
<body>
<h1>Authorized</h1>
</body>
</html>
After creating web pages, now we will write code to authorize the users to use google oauth.
Create a file ‘index.js’.
// importing required packages
const express = require(‘express’);
const passport = require(‘passport’);
const path = require(‘path’);
const GoogleStrategy = require(‘passport-google-oauth20’).Strategy;
const app = express();// defining parameters// client id is the parameter that we will get from the google developer consoleCLIENT_ID=”xxxxxxx”;// client secret will also be taken from the google developer consoleCLIENT_SECRET=”xxxxx”;// user will be redirected to the CALLBACK_URL after authorizationCALLBACK_URL=”http://localhost:8000/authorized”;// port number must be the same as defined in the developer consolePORT=8000;// configuring passport middleware
app.use(passport.initialize());
app.use(passport.session());
passport.serializeUser( function(id, done) {
done(null, id);});
passport.deserializeUser( function(id, done) {
done(null, id);});// following middleware will run whenever passport.
Authenticate method is called and returns different parameters defined in the scope.
passport.use(new GoogleStrategy({
clientID: CLIENT_ID,
clientSecret: CLIENT_SECRET,
callbackURL: CALLBACK_URL
},
async function(accessToken, refreshToken, profile, email, cb) {
return cb(null, email.id);
}));// serving home page for the application
app.get(‘/’, (req, res) =>{
res.sendFile(path.join(__dirname + ‘/public/index.html’));});// serving success page for the application
app.get(‘/success’, (req, res) =>{
res.sendFile(path.join(__dirname + ‘/public/success.html’));});// user will be redirected to the google auth page whenever hits the ‘/google/auth’ route.
app.get(‘/google/auth’,
passport.authenticate(‘google’, {scope: [‘profile’, ‘email’]}));// authentication failure redirection is defined in the following route
app.get(‘/authorized’,
passport.authenticate(‘google’, {failureRedirect: ‘/’}),
(req, res) =>
{
res.redirect(‘/success’);
});// running server
app.listen(PORT, () =>{
console.log(“Server is running on Port ” + PORT)})
Testing Google OAuth
Now our application is ready, and we can test whether it authorizes the users using google oauth.
Go to the root directory and run the application.
ubuntu@ubuntu:~$ node index.js
Now enter the url of your application into the browser.
http://localhost:8000
It shows the home page with an anchor tag.
When we click on the ‘Authorize Here’, it will redirect to the google oauth page.
Your application name ‘Test’ is displayed on the Google authentication page.
When you authorize your account, it will take you to the authorized page.
Conclusion
Managing usernames and passwords for different web applications is not a happy task for users.
Many users leave your web application without registering their account just because they do not want to manage credentials.
The authorization process on your web application or website can be simplified by using third-party services like Google, Facebook, etc.
These services authorize users on their behalf, and the user does not need to manage credentials separately.
In this article, we have implemented the google oauth protocol to authorize users to use Node.js.
Introduction to Making GraphQL APIs and Apps in Node.js
The communication and data transfer between the front end and backend of any application occurs through APIs (Application Programming Interface).
There are many different types of APIs used to communicate between the front and back-end applications like RESTful API, SOAP API, GraphQL API, etc.
The GraphQL API is a relatively new technology, and it is much faster than other types of APIs available.
Fetching data from the database using GraphQL api is much faster than the REST API.
While using GraphQL API, the client has control to fetch only the required data instead of getting all the details; that is why GraphQL API works faster than REST API.
Installing Packages
We will build a node.js application using GraphQL API, so we need to install node.js and npm for this before starting the project.
ubuntu@ubuntu:~$ sudo apt-get update -yubuntu@ubuntu:~$ sudo apt-get install nodejsubuntu@ubuntu:~$ sudo apt-get install npm
Setting up Project
We will use the ‘express’ framework from node.js to build our application.
Create a directory named ‘graphql’ and initiate the project.
ubuntu@ubuntu:~$ mkdir graphqlubuntu@ubuntu:~$ cd graphql/ubuntu@ubuntu:~$ npm init -y
MongoDB Setup
In our GraphQL project, we will use MongoDB as our database.
MongoDB is a schemaless database and stores data in the form of key pairs.
In order to install mongoDB, follow the given steps.
Import the public GPG key for MongoDB.
ubuntu@ubuntu:~$ wget -qO - https://www.mongodb.org/static/pgp/server-4.4.asc | sudo apt-key add -
Create the list file for mongodb.
ubuntu@ubuntu:~$ echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu bionic/mongodb-org/4.4 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-4.4.list
Update local repositories.
ubuntu@ubuntu:~$ sudo apt-get update -y
Install mongodb package.
ubuntu@ubuntu:~$ sudo apt-get install -y mongodb-org
Start and enable mongod.service.
ubuntu@ubuntu:~$ sudo systemctl start mongod.serviceubuntu@ubuntu:~$ sudo systemctl enable mongod.service
Installing npm Modules
For our GraphQL application, we need to install some npm packages.
We will install cors, express, body-parser, mongoose, etc.
ubuntu@ubuntu:~$ cd graphql/ubuntu@ubuntu:~$ npm install cors express body-parser mongoose --save
To create a GraphQL api, we need to install an extra npm package named ‘apollo-server-express.’ This npm package is used to run graphQL server with all Node.js HTTP frameworks like ‘express.’
ubuntu@ubuntu:~$ npm install apollo-server-express --save
Defining MongoDB Schema
Now we have our environment set up for our GraphQL application in Node.js, and it is time to define a schema for our application.
Create a file ‘models/student.js’ in the project root directory.
// defining student schemaconst mongoose = require(‘mongoose’);const studentSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
class: {
type: Number,
required: true
},
major: {
type: String,
required: true
}}, {
timestamps: true});const Student = mongoose.model(‘Student’, studentSchema);
module.exports = { Student, studentSchema }
In the above-defined schema, every student must have a name, class, and major.
Building GraphQL API
After creating the Student schema, we will now build GraphQL API.
Create a ‘schema.js’ to write GraphQL parameters.
There are two parameters, ‘types’ and ‘resolvers,’ used in GraphQL API.
In ‘types,’ we will specify our schema, the queries (e.g., Making GET requests), and mutations (e.g., Making UPDATE or DELETE requests) to the specified schema.
We will write the different methods defined in ‘types’ to link the queries and mutations with the database in ‘resolvers.’
// importing schema and moduleconst { gql } = require(‘apollo-server-express’);const Student = require(‘./models/student’).Student;// Defining Schema, Query, and Mutation Typeconst typeDefs = gql `
type Student {
id: ID!,
name: String!,
class: Int!,
major: String!
}
type Query {
getStudents: [Student],
getStudentById(id: ID!): Student
}
type Mutation {
addStudent( name: String!, class: Int!, major: String! ): Student
updateStudent( name: String!, class: Int!, major: String! ): Student
deleteStudent( id: ID! ): Student
}`// Defining Resolversconst resolvers = {
Query: {
getStudents: (parent, args) => {
return Student.find({});
},
getStudentById: (parent, args) => {
return Student.findById(args.id);
}
},
Mutation: {
addStudent: (parent, args) => {
let student = new Student({
name: args.name,
class: args.class,
major: args.major
});
return student.save();
},
updateStudent: (parent, args) => {
if(!args.id) return;
return Student.findOneAndUpdate({
_id: args.id
},
{
$set: {
name: args.name,
class: args.class,
major: args.major
}
},
{ new: true }, (err, Student) => {
if(err) {
console.log(err);
} else {};
})
}
}}
module.exports = {
typeDefs,
resolvers}
Creating GraphQL API Server
Now we are almost done creating the GraphQL Application.
The only step left is to create the server.
Create a file named ‘app.js’ to configure server parameters.
// importing required packagesconst express = require(‘express’);const mongoose = require(‘mongoose’);const bodyParser = require(‘body-parser’);const cors = require(‘cors’);const { ApolloServer } = require(‘apollo-server-express’);// importing schemaconst { typeDefs, resolvers }= require(‘./schema’);// connecting to MongoDBconst url = “mongodb://127.0.0.1:27017/students”;const connect = mongoose.connect(url, { useNewUrlParser: true });
connect.then((db) => {
console.log('Connection Successful');}, (err) => {
console.log(err);});// creating serverconst server = new ApolloServer({
typeDefs: typeDefs,
resolvers: resolvers});const app = express();
app.use(bodyParser.json());
app.use(‘*’, cors());
server.applyMiddleware({ app });
app.listen( 8000, () =>{
console.log('listening to 8000');})
Testing the GraphQL API
We have our graphQL server up and running on port 8000, and it is time to test the GraphQL API.
Open the GraphQL webpage in the browser by visiting the following url.
http://localhost:8000/graphql
And it will open the following webpage.
Add the student to the database using graphQL API.
Similarly, add more students, and after adding the student, get all the students using GraphQL API.
Note the ID of any of the Students and get the specific student using its id.
Conclusion
Fetching data from the database using the standard REST API makes the query slow as sometimes we get more data than required.
Using GraphQL, we can fetch exactly the required data that makes the GraphQL API faster.
In this demo project, we only have a single schema, so we have created GraphQL API for that single schema.
Also, we have defined three to four methods for the schema.
You can create more than one query or mutations according to your application.
How to Deploy GraphQL Application Using Node.js on EC2 Server
GraphQL, also known as Graph Query Language, established and maintained by Facebook, is a query language used for APIs.
It is built using JavaScript, Scala, Java, and Ruby programming languages.
Its basic purpose is to ask for the data from server to client.GraphQL aggregates the data from different sources.
Aggregation is the process of filtering data on the server side and then sending the filtered data to the client.
Without aggregation, we send all the data to the client, and then the data is filtered at the client-side.
This makes the system slow, and we can improve the efficiency of an API by using GraphQL.
Here we will learn to deploy a simple GraphQL application using node.js on an EC2 server.
Installing Required Packages
The first step to deploy your graphQL application is to ready your server by installing the required packages.
Log in to the server using SSH.
ubuntu@ubuntu:~$ ssh ubuntu@IPAdress -i KeyPair.pem
NOTE: Make sure the security group of the instance is configured to allow connection from port 22 and the private key file has 400 permission.
Update Ubuntu repositories.
ubuntu@ubuntu:~$ sudo apt-get update -y
Now install node.js and npm on your ubuntu server.
ubuntu@ubuntu:~$ sudo apt-get install nodejs -yubuntu@ubuntu:~$ sudo apt-get install npm -y
Verify the installation by checking the version of node.js and npm.
ubuntu@ubuntu:~$ node -vubuntu@ubuntu:~$ npm -v
Move GraphQL Application to EC2 Server
The EC2 instance is ready to deploy graphQL applications in node.js.
Now we will move our code to the EC2 instance.
Two common ways to copy the code to the server are listed below and will be discussed here.
Copy code using scp command
Clone application code from Github, Gitlab, or Bitbucket
Copy Application Using scp Command
In order to copy your application to the EC2 server using the scp command, First of all, remove the ‘node_modules’ directory from your graphQL application.
This directory has all the npm packages required to run the application.
We will install these packages later before starting the graphQL application.
Now compress the project directory into a zip file.
After creating the zip file, we will move the project zip file to the server.
Linux and windows have different methods to create a zip file.
Windows
In windows, right-click on the application root directory and go to the ‘send to’ option.
It will open a submenu.
Click on the ‘Compressed (zipped) folder’ to create a zip file of the graphQL application.
Linux or Mac
In Linux or Mac OS, we will use the ‘zip’ command to create a zip file of the project.
ubuntu@ubuntu:~$ zip -r graphQL.zip graphQL
The above command will generate the graphQL.zip file of the graphQL directory.
Upload Application to the Server
Now we have a zip file of our application, and we can upload the zip file to the server by using the scp command.
ubuntu@ubuntu:~$ scp -i KeyPair.pem graphQL.zip ubuntu@IPAddress:~/
The above command will move the project zip file to the remote server’s home directory over the ssh connection.
Now on the remote server, unzip the project zip file.
ubuntu@ubuntu:~$ unzip graphQL.zip
Clone Application From Github, Bitbucket or Gitlab
The second method to copy application code to the server is using git.
Install git from the command line on the EC2 server.
ubuntu@ubuntu:~$ sudo apt install git
Check the git version to verify the installation.
ubuntu@ubuntu:~$ git --version
If it does not give the version of git, then git is not installed.
Now clone the application from the github, gitlab, or bitbucket.
Here we will clone the application code from the github.
ubuntu@ubuntu:~$ git clone ttps://github.com/contentful/the-example-app.nodejs
Starting the GraphQL Application
Now we have our graphQL application on the remote server.
Go to the root directory of the graphQL application and install the required npm packages to run the graphQL application.
ubuntu@ubuntu:~$ cd graphQLubuntu@ubuntu:~$ sudo npm install
This command will analyze the package.json file in the project and install all the required npm packages.
After installing the required packages, now we will start the graphQL application.
ubuntu@ubuntu:~$ node app.js
Running Application as Daemon
When we run the application using the standard method as described above, it runs in the foreground, and the application stops when you close the terminal window.
We can run the application as a background process by appending the ampersand (&) sign to the command.
ubuntu@ubuntu:~$ node app.js &
The problem with this method is that when we modify our application code, the applied changes will not reflect automatically.
We will have to restart the application every time we modify the code to apply the changes.
In order to run the application in the background and to apply changes automatically, we will use an npm package named pm2.
Install pm2 on the server.
ubuntu@ubuntu:~$ sudo npm install -g pm2
Start the graphQL application using pm2.
ubuntu@ubuntu:~$ pm2 start app.js --name “graphQL” --watch
The ‘–name’ flag will name the background process, and we can start and stop the application using the name.
The ‘–watch’ flag will go on checking the application code to apply changes immediately.
You can learn more about pm2 by visiting the following link
https://pm2.keymetrics.io/
Querying GraphQL API from Browser
We can configure our graphQL application to make graphQL queries from the browser manually.
For this, we have to create a separate HTTP endpoint on which we will mount the graphQL API server.
And this HTTP endpoint will be used to make manual queries.
Following is the code to create the graphQL api server endpoint.
const express = require(‘express’);
const { graphqlHTTP } = require(‘express-graphql’);
const { buildSchema } = require(‘graphql’);
const graphQLSchema = buildSchema(`
type Query{
message: String
}`);
const func = {
message: () =>
{
return ‘you are using graphql api server’;
}};
const server = express();
server.use(‘/graphql’, graphqlHTTP({
schema: graphQLSchema,
rootValue: func,
graphiql: true}));
server.listen(3000);
Now, after running the server, we can access the graphQL api server on the following route.
http://localhost:3000/graphql
Querying GraphQL API Using CLI
In the previous section, we made graphQL queries from the browser using graphiql.
Now we are going to make graphQL queries using the command-line interface in ubuntu.
From the command line, to make an HTTP POST request, we will use the curl module.
ubuntu@ubuntu:~$ curl -X POST -H "Content-Type: application/json" -d '{"query": "{ message }"}' http://localhost:3000/graphql
Querying GraphQL API Programmatically
In order to make graphQL query programmatically, we will use the ‘node-fetch’ module in node.js.
Open node.js in the terminal.
ubuntu@ubuntu:~$ node
Now make the HTTP POST request to the server using the ‘node-fetch’ module.
GraphQL is an efficient query language, and it can decrease the response time of a query made to the database.
The standard api calls to fetch data from the database involve many unuseful data in the response, and hence response time increases, which decreases the efficiency.
The query made to the databases using GraphQL returns only the useful data and hence decreases the response time.
In this article, we have deployed our graphQL application on an EC2 instance.
WebSocket Example Program
The WebSocket protocol allows for two-way communication to occur between a client and a server.
This process is similar to the way in which calls on your phone take place: first, you establish a connection, and then you can start communicating with one another.
The WebSocket protocol is used almost everywhere – from multiplayer browser games to chat applications.
This article shows you how to create a WebSocket protocol and use it to communicate with multiple users.
Prerequisites
Before moving on to the process of creating and using a WebSocket protocol, you first need to install a few things that are required for this process.
The first thing that you need to install is Node.js, a server-side platform that converts the JavaScript programming language into machine code that allows you to run JavaScript directly on your computer.
To install Node.js, Windows users can simply go to the official Node.js website and click on the green LTS button found in the center of the screen.
For Linux and macOS users, click on the Downloads section in the sub-header of the website.
After opening the Downloads section, you will see installation files for all three major platforms.
Select a package that is supported by your system.
Run the installer that comes with the downloaded files, and Node.js will be installed on your computer.
To check whether the program has been installed, open the terminal and issue the following command:
$ node -v
After installing Node.js, you now have access to various JavaScript modules, which will make your work more efficient in the long run.
Open the directory in which you want to create your client and server architecture, then open the terminal inside that directory and run the following command:
$ npm init -y
This command is used to create the package.json file that allows you to set up and install different Node.js packages.
Install the WebSocket protocol package by issuing the following command in the terminal:
$ npm install ws
Create three files, called index.html, client.js, and server.js.
As indicated by the names, these JavaScript files are the client and server architecture of our WebSocket protocol.
Now, we can finally start writing the code of our client and server applications.
Creating a WebSocket Server
To create a WebSocket server, we will start by writing the code for the server.
Open the server.js file that you created inside your text editor or IDE in the previous section and enter the following lines inside the file.
const WebSocket = require('ws');const ws = new WebSocket.Server({ port: 8080 });
console.log("Server Started");
ws.on('connection', (wss) => {
console.log("A new Client Connected")
wss.send('Welcome to the Server!');
wss.on('message', (message) => {
console.log(`Server Received: ${message}`);
wss.send('Got your Message: ' + message);
});});
Now, we will explain what each line is doing in greater detail.
Code Explanation
As mentioned previously, there are some built-in modules available in Node.js that make your work much easier.
To import these modules, we will use the require keyword.
const WebSocket = require('ws');const ws = new WebSocket.Server({ port: 8080 });
console.log("Server Started");
The first line is used to import the Node.js WebSocket module.
Using this module, in the next line, we create our WebSocket server, which is listening on port 8080.
The console.log() line is simply there to let us know that the Server has started.
You will see this appear inside your terminal when you run the following command in the terminal:
$ node server
In the next line, we are establishing a connection between the server and the client.
ws.on('connection', (wss) => {
console.log("A new Client Connected")});
After a connection has been established, the wss.send() line sends a message to the client.
In this case, the message is “Welcome to the Server.”
wss.send('Welcome to the Server!');
Finally, the wss.on (‘message’) is for the server to receive the message from the client.
For confirmation, the server sends this message back to the client in the last line.
wss.on('message', (message) => {
console.log(`Server Received: ${message}`);
wss.send('Got your Message: ' + message);
});
Creating a WebSocket Client
For the client-side, we need both the index.html file and the client.js file.
Of course, you can simply add the content from the client.js file into your index.html file, but I prefer keeping them separate.
Let us first look at the client.js code.
Open the file and enter the following lines inside of the file:
const socket = new WebSocket('ws://localhost:8080');
socket.addEventListener('open', () => {
console.log('Connected to the Server!');});
socket.addEventListener('message', (msg) => {
console.log(`Client Received: ${msg.data}`);});const sendMsg = () => {
socket.send('Hows it going amigo!');}
Code Explanation
Like with the server.js, we will create a new WebSocket that is listening to port 8080, which can be seen in the localhost:8080 section of the code.
const socket = new WebSocket('ws://localhost:8080');
In the next line, addEventListener makes your client listen to any events that are currently happening.
In this case, it would be creating and starting the server.
Once the connection is established, the client outputs a message to the terminal.
socket.addEventListener('open', () => {
console.log('Connected to the Server!');});
Once again, the client listens to any events currently happening.
When the server sends a message, the client receives this and then displays the message in the terminal.
socket.addEventListener('message', (msg) => {
console.log(`Client Received: ${msg.data}`);});
The last few lines are simply a function where the client is sending a message to the server.
We will connect this to a button in our html file for a better understanding of how this is working.
const sendMsg = () => {
socket.send('Hows it going amigo!');}
Preparing an HTML File
Finally, open the index.html file and add a reference to your client.js file inside of it.
In my case, I will simply add the following lines of code:
<!DOCTYPE html><html lang="en"><head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Client</title></head><body>
<button onClick="sendMsg()">Send Message to Server</button></body><script src="client.js"></script></html>
As you can see in the lines below, src (inside the script tag) refers to the client javascript file.
The sendMsg function, which was created in the client.js file, has also been connected to the button’s onClick function.
<button onClick="sendMsg()">Send Message to Server</button>
<script src="client.js"></script>
Putting Everything Together
You can now start testing your Client and Server Architecture.
First, open the terminal and run the following command to start your server:
$ node server
After starting your server, open the directory in which your index.html file is present, and double-click on it to open it in your browser.
You will see the following message appear in the terminal stating that a client has connected:
You can also check the messages sent from the server to the client by pressing the right-click button and then opening the Inspect window.
In this window, click the Console section, and you will be able to see the messages sent from the server.
Once you click on the button, both the server and client will be able to send and receive messages to and from each other.
Server:
Client:
Voilà, your WebSocket connection has been established!
Conclusion
The WebSocket protocol is an excellent way to establish communication between a client and a server.
This protocol is used in several fields, including multiplayer browser games, chat systems of various social media platforms, and even collaboration processes between coders.
Vue.js vs.
Django
When you are required to choose a library or framework for building web applications, there is no question that JavaScript libraries are preferred over any other library.
But that does not mean that other libraries are not good enough.
Vue.js and Django are both famous JavaScript web frameworks.
They are also both open-source tools.
Vue.js is famous for building clean, reusable, component-based web applications.
Django is a framework that is built on Python and is known for its rapid development and rational code design.
In this article, we will discover some of the basic and more technical differences between Vue.js and Django.
This includes the pros and cons of each framework, the companies that currently use these frameworks, integrated tools, and much more.
Difference between Vue.js and Django
Vue.js is a front-end JavaScript framework that generates pages on the client-side.
Because it renders pages on the client-side, Vue.js costs more initial load time, but it gives a better experience when it is necessary to navigate between pages.
While Django is a full-stack Python framework and it generates pages on the server-side.
Its server-side rendering helps in initially loading the page but while navigating we may have to face performance issues due to the network latency.
Pros of Vue.js
Vue.js is a simple, easy-to-use, and fantastic library for your needs.
You can learn it hands-on if you know Html, CSS, and JavaScript.
Vue.js is a framework with a fast learning curve signature.
The documentation written for Vue.js is also easy to understand and extremely detailed, as well.
The documentation is so well written that you should not feel confused, even when working with it all day.
All steps are explained clearly and the Vue.js documentation is one of the best guides available for any web framework.
Vue.js is a complete and functional JavaScript ecosystem, and it stands as one of the top front-end frameworks.
Pros of Django
Django is known for its rapid development, and it is an open-source tool.
This framework has a great community, as well.
Django is an elegant MVC Framework that helps you in writing beautiful code.
This framework is free to use, has great documentation, and is very easy to learn, as well.
It also provides great packages and libraries to help in development.
Cons of Vue.js
The community of Vue.js is smaller than the other two competitive frameworks, reactJS and Angular.
Vue.js does not support fragments, and it only supports multiple root nodes programmatically.
Another con of Vue.js is its YXML vs.
HTML markup.
Cons of Django
Django is an underpowered templating framework and has an underpowered ORM.
Its auto-reload restarts the whole server.
Django’s URL dispatcher ignores the HTTP method and has some coupling of internal subcomponents.
Having cons does not necessarily mean that a framework is bad.
Actually, every framework comes with the intention of fulfilling some particular need or providing some specific value.
It is a well-known fact that every framework has its own features and standards that differentiate it from other frameworks, and it is easy to prioritize one over another according to your needs.
Companies that Use Frameworks
Both of these frameworks are backed by good companies.
Vue.js is backed by a lot of big names, such as:
Alibaba
Xiaomi
Laracast
Trivago.com
Django is also backed by some big names, such as:
Pinterest
Instagram
Udemy
Robinhood
Conclusion
In this article, we reviewed both the Vue.js and Django frameworks and pointed out their differences.
We also discussed the pros and cons of each framework and mentioned the name of the companies backed by these frameworks.
Vue.js is becoming quite popular among JavaScript frameworks and front-end web development at an increasing pace, specifically in terms of single-page applications and user interfaces.
Meanwhile, Django will have its own recognition of being a full-stack and rapid development framework.
Vue.js Router
Vue.js is a reactive javascript framework, which is used to build UIs(User Interfaces) and SPAs(Single-page Applications) and developers love to code and feel freedom and comfort while developing applications in Vue.js.
For routing purposes, Vue.js does not provide the built-in routing feature.
But there is an official third party library with the name of Vue Router for providing this feature.
By using this feature we can navigate between the web pages but without reloading.
So, in this article, we are going to see how we can install and use Vue Router in Vue.js.
Installation
We can install the Vue router into an existing Vue.js project by running the following command in the terminal
npm install vue-router
After a successful installation, we need to import VueRouter in the main.js file in the src directory as well using the following syntax
import Vue from 'vue'import router from './router'
Vue.use(router)
After importing the router, you are good to go and use vue-router in your project.
But if you are installing Vue.js using Vue CLI.
You won’t need this extra installation step.
You can add a vue-router plugin during selecting a preset.
Usage
The usage of the vue-router is very simple and easy to use.
First, in the template or HTML
<template><div id="nav"><router-link to="/">Home</router-link> |<router-link to="/about">About</router-link></div><router-view /></template>
In this pretty simple and clear example of vue-router.
We have created simple navigation using router-link components and provide the link using the prop named ‘to’.
The router-link works the same as an anchor ‘a’ tag.
It is actually rendered as an ‘a’ tag by default.
In the router-view, we will have the relative component which matches the route.
In the javascript, we first have to register and import the components to define their routes.
We suppose that we have a component named Comp.vue in the views directory to which we will import in the router’s index.js file in the router directory and define it as a route.
To import a component, we use the following statement
import Comp from "../views/Comp.vue";
After importing, we have to define the route now and map it to the component.
Like this,
const routes = [{
path: "/",
name: "Comp",
component: Comp}];
We can give multiple routes too, separated by a comma.
Like this,
const routes = [{
path: "/",
name: "Comp",
component: Comp},{
path: "/comp2",
name: "Comp2",
component: Comp2}];
After defining the routes.
Pass routes array to the router instances.
So, let’s create the router instance as well
const router = createRouter({
routes // short for `routes: routes`});
In the end, in the main.js file.
We have to create the root instance and mount that as well and inject the routes in it so that the whole app becomes aware of the routes.
createApp(App)
.use(router)
.mount("#app");
By using this injection technique.
We can access the router in any component, using this.$router .
We can now programmatically push routes at the click of a button or anything you want, instead of using the router-link component.
For example,
methods: {
clickFunc() {this.$router.push('/about')}}
Wrapping up and summary
In this article, we have learned to install Vue Router using different ways and learned to use Vue router programmatically and in the Vue.js’s template.
We have also learned to set up the Vue Router in an existing project in a very easy and step by step detailed guide.
If you want to learn more about the Vue Router, kindly visit Vue Router: Official Docs.
Vue.js Emit Custom Events
Vue.js is a versatile and full-fledged framework for building huge web applications.
Any web application is divided into the Components.
For example, a simple website that includes a header, sidebar, and some other components.
In order to manage and handle this component-based approach, Vue.js offers the parent-child relationship between the components and if we want to send some data across components.
Vue.js offers props to send data from the parent to a child component but to send data from the child to the parent; we have to emit custom events.
In this article, we learn about firing and listening to custom events.First of all, let’s see how to fire a custom event in Vue.js and then how to listen to that event.
The syntax for firing an event in Vue.js is
this.$emit('eventName')
In this syntax, we need to be careful while giving a name to the event because using the same name; we will later listen to this event.
In order to listen to this event, we can listen to it as we listen to a click event in Vue.js.
For example
<myComponent @eventName="doSomething"></myComponent>
We can write any expression in the inverted commas as well as a function.
So let’s try an example to better understand it.
Example
Suppose we have a Component named “parentComponent,” which includes a child component in it with the name of “childComponent” to which we are passing a message using props.
<template><h1>Parent Component</h1><div><h2>Child Component</h2><ChildComponent msg="Hello Child" /></div></template><script>import ChildComponent from './components/ChildComponent.vue'export default {
name: 'ParentComponent',
components: {
ChildComponent}}</script>
In the child Component, we are getting props and showing the message in the ‘p’ tag.
<template><p>{{ msg }}</p></template><script>export default {
name: "ChildComponent",
props: {
msg: String}}</script>
Now after having these two components set up.
Let’s say hello back to our ParentComponent.
In order to say hello back, we will first create a button, and at the click of that button, we will call the “helloBack” function.
After creating the button, the child component’s HTML would be like this
<template><p>{{ message }}</p><button @click="helloBack">Send Hello Back</button></template>
Let’s create the “helloBackFunc” function in the methods object as well.
In which we will emit the “helloBackEvent” along with a “helloBackVar” variable that contains the string “Hello Parent”.
After creating a function, the javascript of the child component would be like this
<script>export default {
name: "ChildComponent",
props: {
msg: String},
data(){return{
helloBackVar: 'Hello Parent'}},
methods:{
helloBackFunc(){this.$emit('helloBackEvent', this.helloBackVar)}}}</script>
We are done with firing the event.
Now, let’s move to the parent component for listening to the event.
In the Parent component, we can simply listen to the event, just like we listen to the click event.
We will simply listen to the event in the ChildComponent’s tag and calls the “thanks()” function on it.
<ChildComponent @helloBackEvent="thanks($event)" msg="Hello Child" />
In the thanks function, we will assign the passed string to the variable named “thanksMessage”.
After creating the function and assigning the passed string to the variable, the javascript of the “parentComponent” would be like this
<script>import ChildComponent from './components/ChildComponent.vue'export default {
name: 'App',
components: {
ChildComponent},
data(){return{
thanksMessage: ''}},
methods: {
thanks(m){this.thanksMessage = m;}}}</script>
And bind the “thanksMessage” variable in the template somewhere to see either it works or not.
<template><h1>Parent Component</h1><p>{{ thanksMessage }}</p><div><h2>Child Component</h2><ChildComponent @helloBackEvent="thanks($event)" msg="Hello Child" /></div></template>
After creating and writing all this code, go to the web page and reload it to get the latest functionalities.
We can see that the props are conveyed successfully to the child component.
Now, if we click the button, which is actually in the child component.
The thanks message should be displayed right after the parent Component Heading.
As you can see, it is displayed.
So, this is how we can emit or fire the custom events and listen to them in some other component in Vue.js.
Summary
In this article, we have learned to emit custom events in the Vue.js.
This article contains a step by step proper example to understand it with a brief explanation along with it.
So, we hope this article helps in having better and clear concepts of emitting custom events in Vue.js.
For more such useful content, keep on visiting linuxhint.com
What is Vue.js, and Why is it Cool?
Vue.js is a progressive JavaScript framework, which is used to build UIs (User Interfaces) and SPAs (Single-page Applications).
This framework is famous for its fast-paced learning curve.
It is such an easy to learn and approachable library that with the knowledge of HTML, CSS, and JavaScript, we can start building web applications in Vue.js.
The fast learning curve is kind of a signature of this framework.
It is a versatile framework for our need as a library or a full-fledged framework for building huge web apps.
Evan You have created this framework.
The idea of Evan You behind this framework is to build the best framework by combining the best features from already existing Angular and react Frameworks.
Before building Vue.js, Evan You was working at Google.
Inc and worked on Angular based projects.
So, he came up with the idea of building his own framework.
He picked the best parts of Angular, like template syntax, easy to use, and picked the best parts of React as well, like two-way data binding, the concept of props, component-based approach, and combined them to make a new framework Vue.js better than both of them.
Competition
Every framework has its own features and characteristics, because of which they are known and get priority over any other framework.
Vue.js has a record of having the most stars at Github.com for the past 5 years.
Although the community of Vue.js is smaller than the react JS, Vue.js stars record is describing and telling about the fans of Vue.js.
Whoever uses it once, he/she falls in love with it.
Evolution and Growth
Vue was released way back in 2014.
Since then, it is continuously evolving.
At the beginning of 2018, Vue.js started beating Angular and becoming more famous in the market.
Later, in September 2018, Evan You decided to announce the release of Vue 3.0.
Vue.js is continuously evolving with the rapid growth in the usage and community of this framework.
The community will keep growing because it was built on the best features combination of Angular and React.
Here are some of the features that we find exciting and the root cause of its rapid growth and make it cool.
Learning Curve & Well written Documentation
Vue.js has one of the best-written Documentation that we have ever seen and suggested.
This Documentation takes us through an effortless and step by step guide that one doesn’t feel like hard learning or something different is happening.
The learning curve is effortless if we compare it with the react.JS and Angular.
Modular and reusable code
This component-based approach was basically inspired by and picked from the ReactJS.
We write code in the form of components to import that component and reuse it wherever we need it.
Vue.js offers a single-file component, which makes it a loosely coupled and reusable code.
Mobile Development
There is one underrated feature of Vue.js, which is its cross-platform mobile development.
Yes, just like react-native works for react.JS.
Vue.js has WEEX developed by Alibaba, Native Script, and Ionic to help in developing mobile UIs.
Native Script and WEEX claim that you just have to write the code once and then use/run it wherever you want.
Easy Development
Developers love to code or build applications in Vue.js.
They feel freedom and comfort while developing in an unopinionated environment.
Vue.js offers the best component-based approach like whatever a developer needs; he can find it in a single .vue file.
Developers feel so comfortable and at ease when they don’t have to worry about or take care of the extra structure of a component.
Ecosystem for Development
Vue.js has a very active and vibrant community, which is helping a lot in evolution and growth.
Vue.js provides a lot of different tools and libraries to facilitate the development process.
The community has some remarkable and note tools and libraries that a coder or developer demands.
For example,
Vue Router is used for any type of routing.
Vuex is used as a centralized store for state management.
Summary
Vue.js is an easy, fast-growing, and adaptable framework to implement in developing applications that anybody with the basic knowledge of web development can get started with because of its invisible learning curve and easy to understand Documentation.
Vue.js provides a full-fledged ecosystem, and it is counted in the top 3 JavaScript front-end frameworks.
Honestly, it is the best framework it can be.
It is backed by a lot of big names like Alibaba, Xiaomi, and Lara cast.
So, it is a must-try framework if you have not tasted it yet.
Vue.js Conditional Rendering
Vue.js is an easy to learn and approachable library that we can start building web applications in it with the basic knowledge of web development.
In Vue.js, developers love to code and feel freedom while developing applications.
In any dynamic web application, conditional rendering is a necessary part.
Vue.js provides different ways for conditional rendering, and we can use any of the following ways which suit our purpose:
v-show
v-if
v-else
In this article, we will try these directives provided by Vue.js for conditional rendering and understand them in a better way.
v-show
The v-show only hides the element by disabling its visibility.
It hides the element if the value of the passed expression or variable is not truthy.
For example:
<p v-show="isBool">This paragraph is not hidden</p><p v-show="!isBool">This paragraph is hidden</p>
v-if
On the other hand, v-if does not hide the element, but it also does not render anything until the value of the passed expression or variable becomes true.
For Example:
<!-- This div is conditionally rendering -->
<div v-if="isBool">
<p>This is a paragraph</p>
</div>
There is an additional feature in the v-if directive as compared to the v-show directive.
We can apply it to the template block as well if we do not want to render anything in between that block.
Either there is a child component in that or a lot of other elements.
For example:
<!-- This template is conditionally rendering -->
<template v-if="isBool">
<h1>This is a Heading</h1>
<p>This is a paragraph</p>
<!-- A child component -->
<Hello msg="Hello Vue" />
</template>
v-else
We can also use the v-else directive along with the v-if statement in order to conditionally render between any of the two blocks.
But, keeping in mind that the v-else block must have to appear right after the v-if block.
For example:
<p v-if="isVar == true">This paragraph will render if 'isVar' becomes true</p>
<p v-else>Else, this paragraph will get rendered.</p>
We can apply v-else on the template block as well.
<!-- This div is conditionally rendering -->
<div v-if="isVar == true">
<h1>This is a Heading</h1>
</div>
<!-- v-else on template block -->
<template v-else>
<p>This is a paragraph</p>
<!-- A child component -->
<Hello msg="Hello Vue" />
</template>
v-else-if
Just like v-else, we can also use the v-else-if directive along with the v-if directive.
For example:
<div v-if="type == 'car'">
<p>Car</p>
</div>
<div v-else-if="type == 'book'">
<p>Book</p>
</div>
<div v-else-if="type == 'animal'">
<p>Animal</p>
</div>
<div v-else>
<p>None of the ablove</p>
</div>
v-if vs.
v-show
The v-if and v-show kind of do the same task.
They both hide the elements in the DOM based on the truthy or falsy value of the passed expression, but with a subtle difference of hiding and not rendering elements.
If we compare the time and processing cost between these two.
The v-if costs more during runtime or toggling, while v-show costs more at the start of rendering.
So, it would be wise to use v-show when toggling is purpose.
Otherwise, v-if is preferred.
Wrapping up
In this article, we have learned how to conditionally render the DOM in Vue.js using v-if and v-else directives.
We have shown some examples and learned about the real difference between v-show and v-if directive.
If this article helps you to have a better understanding and concepts, keep on visiting linuxhint.com for such useful content.
Vue.js Change Style
Vue.js is used to build User Interfaces (UIs) and Single-Page Applications (SPAs).
It is easy to learn how to use Vue.js and the framework of freedom and comfort that is available while developing applications in this program because it has the best-combined features of Angular and ReactJS.
That is why it is known for its easy-to-use and clean coding.
Vue.js provides style binding that you can use to change the style dynamically.
You can bind a variable to the style attribute in any HTML tag and change the style when the bound variable is changed.
In this article, we will have a look at how to use style binding and change the styling of variables using vue.js.
Inline Style Binding
In vue.js, we can bind variables to style attributes using v-bind directives.
Object Syntax
Just like with inline CSS styling, we can also do inline styling in Vue.js using v-bind directive and curly braces object syntax.
You can bind any variable to the style attribute using the following script:
<p :style="{ color: colorVar, fontSize: fontSizeVar + 'px' }"></p>
And, in the script tag and data:
ata() {
return {
colorVar: 'red',
fontSize: 14
}}
We can also take the object down to the data and bind that object with the style attribute to make our HTML look cleaner as follows:
data() {
return {
styleObject: {
colorVar: 'red',
fontSize: 14
}
}}
Now, we will bind the “styleObject” variable to the style attribute as follows:
<p :style="styleObject"></p>
Array Syntax
Vue.js also provides the option to bind multiple variables in array syntax to the single HTML tag, as follows:
<p :style="[basicStyling, extraStyling]"></p>
Multiple Values
Similarly, we can also give multiple values using the array syntax to a CSS property within the inline binding, as follows:
<div :style="{ display: ['-webkit-box', '-ms-flexbox', 'flex'] }"></div>
These are some of the different ways that we can use for binding variables with the style attribute to dynamically change the styling of a webpage.
Summary
This article covered the syntax for binding inline styling.
You also learned about the object syntax and array syntax used to bind the values or variables to style attributes in vue.js.
If this article proved helpful in giving you a better understanding of vue.js, feel free to continue reading at linuxhint.com for more useful content.
Vue.js Click Events
Vue.js is a very powerful, easy to learn, and approachable library that with the knowledge of HTML, CSS, and Javascript, we can start building web applications in it.
Vue.js is built by combining the best features from already existing Angular and react Frameworks.
It is a progressive and reactive Javascript framework that is used to build UIs (User Interfaces) and SPAs (Single-page Applications), which is why the developers love to code and feel freedom and comfort while developing applications in Vue.js.If we take a look at the Event Listening and Handling in Vue.js., we will know that it provides a “v-on” directive to listen and handle events.
We can use the “v-on” directive to listen to the DOM and perform the required tasks.
It also provides many event handlers.
However, in this article, we will only learn and keep our focus on the click events.
So, let’s get started!
Just like Javascript’s onClick event, Vue.js provides v-on:click for listening events.
The syntax for v-on:click event would be like this:
<button v-on:click="functionName">Click</button>
Vue.js provides a shorthand “@” instead of using “v-on” as well.
<button @click="functionName">Click</button>
Vue.js doesn’t stop in just listening to the click event and calling the function.
It will also allow us to directly write any arithmetic operation or anything related to Javascript inside the quotation marks “ ”.
Just like this:
<button @click="num += 1">Add</button>
Vue.js provides us to call the method or function in an inline Javascript statement, as shown below:
<button @click="message('Hi')">Show</button>
Using Vue.js’s event handlers, we can access the DOM event as well, using inline statement, by passing the Vue.js’s especially provided “$event” variable into the method’s argument, just like the example below:
<button @click="message('Hi', $event)">Send</button>
Vue.js also provides us to call multiple functions or methods.
We can call more than one function and separate them by commas, like this example:
<button @click="first('Hello'), second('Hi', $event) ">Submit</button>
Vue.js provides event modifiers as well.
Event Modifiers
We often need to call modifiers along with the events.
So, Vue.js provides some of the following modifiers:
.stop
It will stop the click event’s transmission.
<a @click.stop="doThis"></a>
.prevent
It will prevent the page to reload or redirect.
<form @submit.prevent="onSubmit"></form>
.once
It will trigger the click event only once.
<a @click.once="doThis"></a>
.capture
It is mostly used to add the event listener.
<div @click.capture="doThis">...</div>
We can chain the modifiers as well.
However, keep in mind that the order of modifiers does matter, and it will affect the results.
<a @click.stop.prevent="doThat"></a>
Conclusion
In this article, we have covered the whole Click event handling concepts from noob to ninja level.
We have learned about the different syntaxes of writing click events and the different ways to use v-on:click directive provided by Vue.js for the ease of developers and different event modifiers.
For more useful content like this, related to Vue.js, keep on visiting linuxhint.com.
Vue.js Components
Vue.js is a progressive javascript framework, which is used to build UIs(User Interfaces) and SPAs(Single-page Applications).
We can start building web applications in Vue.js with the basic knowledge of HTML, CSS, and Javascript.
Vue.js is built by combining the best features from already existing Angular and react Frameworks.
Developers love to code and feel freedom and comfort while building applications in Vue.js.
This component-based approach was basically inspired by and picked from the ReactJS.
We write code in the form of components so that we can import that component and reuse it wherever we need it.
Vue.js offers a single-file component, which makes it a loosely coupled and reusable code.
Vue.js offers the best component-based approach, like whatever a developer needs; he can find it in a single .vue file.
Developers feel so comfortable and at ease when they don’t have to worry about or take care of the extra structure of a component.
In this article, we will have a look at the single-file component, which has a .vue extension.
So, let’s have a look at a very simple Vue component example and understand it.
<template>
<p>{{ message }} World</p></template><script>export default {
name: "hello",
data(){
return{
message: "Hello"
}
}}</script><style>
p {
font-size: 1em;
text-align: center;}</style>
This a very simple and basic example of a Vue component.
In which we can see that the code is divided into three layers.
This three-layer syntax is the best part of Vue.js.
It satisfies the separation of concern yet being in one single .vue file.
We have our template(HTML), logic, and styling inside a component.
Template
Script
Style
Template
In this template tag, we write our HTML code.
We can bind variables in this as well using the Vue.js data-binding syntax, and we can add some other functionalities in this as well using the Vue.js provided syntax for the respective functionalities.
Script
This is the section where we can write the logic of the component by following the syntaxes of Vue.js.
All the functionalities and logic of a component go here.
For example,
Importing other components and packages needed.
Variable declaration
Methods/Functions
Life cycle hooks
Computed properties and watchers
And so on…
Style
This is where we write the styling in CSS of the component, or we can use any preprocessor we want to use.
This is just a glimpse of a component in Vue.js.
Let’s take a look at the usage, organization, and data flow between components a little bit.
Import and Use Components
To use the component, we first have to import the component.
Otherwise, how can Vue.js know about it? We can simply import a component by adding an “Import” statement at the beginning of the script tag and declaring that component in the “components” object, using the following syntax.
<script>import Hello from './components/Hello.vue'export default {
name: 'App',
components: {
Hello
}}</script>
After importing the component successfully, we can use it in the template like this
<Hello msg="Hello Vue" />
This is how simply we can import and use a component in any other component.
Organizing Components
Just like any other application, the Components organization goes like a nested tree.
For example, a simple website that includes a header, sidebar, and some other components in a container.
The organization of the component would be like this.
Image from Vue.js Official Docs
Data Flow between Components
There can be two types of data flow between components: Parent component to Child Component
We can send data from the parent component to the child component using props: Child Component to Parent Component
We can send data by emitting an event from the Child component and listen to it on the other end (Parent component).
Wrapping Up
In this article, we have gone through a whole journey of understanding a basic component in Vue.js to its usage, its hierarchy, its organization, and implementation of Importing, using, and know-how about communication between components.
This article covers a lot of scope of components, yet there is a lot of in-depth knowledge about components out there.
So, feel free to visit the Vue.js Official Docs for more information.
Vue.js Data Binding
Vue.js is such an easy to learn and approachable library.
So, with the knowledge of HTML, CSS, and Javascript, we can start building web applications in Vue.js.
Vue.js is built by combining the best features from an already existing Angular and react Frameworks.
Data binding is one of the most elegant features of Vue.js because it provides reactive/two-way data binding.
In Vue.js, we do not have to write a lot of lines to have two-way data binding, unlike other frameworks.
One-way data binding means that the variable is just bound to the DOM.
On the other hand, two-way means that the variable is also bound from the DOM.
When DOM gets changed, the variable also gets changed.
So, let’s take a look at both of the data bindings and see the right difference.
One-way Data Binding
If we want to bind any variable, we can simply use Vue.js’s double curly braces syntax or “Mustache” syntax to bind any variable from the relative component instance.
<p> {{ linuxhintText }} </p>
Or, if we want to bind any variable inside an HTML attribute, we can use the v-bind directive.
<div v-bind:class="container"></div>
Vue.js also provides the shorthand for binding variables in an HTML attribute.
Instead of writing v-bind:attribute-name, we can only use a colon “:” and attribute name.
<div :class="container"></div>
But these are just data bindings.
To demonstrate the two-way data binding, we can use the v-model directive provided by the Vue.js.
Two-Way/Reactive Data Binding
In order to demonstrate reactive data binding, we can use the v-model directive on an input form field.
It will internally emit an event and change the variable.
To which we can bind somewhere else in the template using Double curly braces or “Mustache” syntax.
<input v-model="linuxhintText" placeholder="Type something" /><p>You are typing: {{ linuxhintText }}</p></td>
Now, whenever we enter a character in the input form field, we can see that the variable is also updating simultaneously.
Wrapping up
In this article, we have learned how to bind variables in Vue.js using double curly braces or “Mustache” syntax.
We have also demonstrated the two way/reactive data binding in Vue.js using the v-model directive.
After reading this article, data binding is not a difficult task anymore for a beginner who has just got a start with Vue.js.
So, keep on learning the concepts of Vue.js with linuxhint.com.
Thank you!
Vue.js Watch Property
Vue.js is a very powerful and reactive Javascript framework, which is used to build Uis (User Interfaces) and SPAs (Single-page Applications).
It is built by combining the best features from already existing Angular and react Frameworks.
Developers also love to code or build applications in it.
Vue.js provides the watch property to observe and react to the variables or data change.
We can use the watch property to manipulate the DOM when the watched variable gets changed.
In this article, we are going to have a look at how we can use watch property, and perform the desired tasks on the change of variable.
So, let’s get started.
Watchers
A watcher in Vue.js acts like an event listener to a variable or property.
It is used to accomplish several tasks on the change of some specific property.
It comes in handy while doing asynchronous tasks.
Let’s demonstrate and understand the concept of the watcher by considering an example.
Example:
Suppose we are building an e-commerce website, in which we have a list of items, and we are building it cart or checkout component.
In that component, we need to calculate the amount of a single element concerning the number of items.
First, we are assuming some properties in the data.
data() {
return {
itemName: "Item 1",
itemQuantity: null,
itemPrice: 200,
totalPrice: 0
}},
In which we will watch the “itemQuantity” property and calculate the total price.
We will first do the data bindings in the template,
before writing the code for watching the variable and calculating the total price.
<template>
<h1>Watcher</h1>
<p>Item Name: {{ itemName }}</p>
<p>Item Price: {{ itemPrice }}</p>
<input type="number" v-model="itemQuantity" placeholder="quantity" />
<p>Total Price: {{ totalPrice }}</p></template>
After writing this code, we will have our web page like this:
Now, we want to change the total price on the change of “itemQuantity” like whenever the user changes the quantity using the input field.
The Total Price should get changed.
For that purpose, we will have to watch the “itemQuantity” and calculate the total price whenever the “itemQuantity” property gets changed.
So, the watcher for the “itemQuantity” would be like this:
watch:{
itemQuantity(){
this.totalPrice = this.itemQuantity * this.itemPrice;
console.log(this.itemQuantity);
}}
Now, whenever the user changes the “itemQuantity”, the total price will be changed in a moment.
We don’t have to worry about anything, anymore.
The watch property will take care of this calculation now.
Let’s have a look at the web page:
And, let’s try to increase or change the quantity and see some results:
If we change the quantity, let’s say “4”, the total price would be “800”:
Similarly, if we change the quantity to “7”, the total price would be “1400”:
So, this is how the watch property works and helps in reactive development.
Reactivity is kind of a signature of Vue.js.
Also, the watch property comes in handy while performing asynchronous operations.
Conclusion
In this article, we have learned what is a watch property and how we can use it in Vue.js.
We have also tried a real-life example to understand its true implementation.
This helps a lot in saving time and speeding up the development process.
We hope that you found this article helpful and keep on visiting linuxhint.com for better understanding.
Setup Electron and Create Hello World Application in Linux
This article will cover a guide about installingElectronand creating a simple “Hello World” Electron application in Linux.
About Electron
Electron is an application development framework used for creating cross-platform desktop applications using web technologies in a standalone web browser.
It also provides operating system specific APIs and a robust packaging system for easier distribution of applications.
A typical Electron application requires three things to work: Node.js runtime, a standalone Chromium based browser that comes with Electron and OS specific APIs.
Install Node.js
You can install Node.js and “npm” package manager by running the following command in Ubuntu:
$ sudo apt install nodejs npm
You can install these packages in other Linux distributions from the package manager.
Alternatively, download official binaries available on Node.jswebsite.
Create a New Node.js Project
Once you have installed Node.js and “npm”, create a new project named “HelloWorld” by running the following commands in succession:
$ mkdir HelloWorld
$ cd HelloWorld
Next, fire up a terminal in the “HelloWorld” directory and run the command below to initialize a new package:
$ npm init
Go through the interactive wizard in the terminal and enter names and values as needed.
Wait for the installation to finish.
You should now have a “package.json” file in “HelloWorld” directory.
Having a “package.json” file in your project directory makes it easier to configure project parameters and makes the project portable for easier shareability.
The “package.json” file should have an entry like this:
"main": "index.js"
“Index.js” is where all logic for your main program would be located.
You can create additional “.js”, “.html” and “.css” files according to your needs.
For the purpose of “HelloWorld” program explained in this guide, the command below will create three required files:
$ touch index.js index.html index.css
Install Electron
You can install Electron in your project directory by running the command below:
$ npm install electron --save-dev
Wait for the installation to finish.
Electron will be now added to your project as a dependency and you should see a “node_modules” folder in your project directory.
Installing Electron as a per-project dependency is the recommended way of installing Electron according to the official Electron documentation.
However, if you want to install Electron globally on your system, you can use the command mentioned below:
$ npm install electron -g
Add the following line to “scripts” section in “package.json” file to finish Electron setup:
"start": "electron ."
Create Main Application
Open “index.js” file in text editor of your choice and add the following code to it:
const { app, BrowserWindow } = require('electron');function createWindow () {
const window = new BrowserWindow({
width: 1600,
height: 900,
webPreferences: {
nodeIntegration: true
}
});
window.loadFile('index.html');}
app.whenReady().then(createWindow);
Open “index.html” file in your favorite text editor, and put the following code in it:
<!DOCTYPE html><html><head><link rel="stylesheet" href="index.css"></head><body><p id=”hworld”>Hello World !!</p></body></html>
The javascript code is pretty self explanatory.
The first line imports necessary Electron modules needed for the app to work.
Next, you create a new window of the standalone browser that comes with Electron and load the “index.html” file in it.
The markup in the “index.html” file creates a new paragraph “Hello World !!” wrapped up in the “<p>” tag.
It also includes a reference link to the “index.css” stylesheet file used later in the article.
Run Your Electron Application
Run the command below to launch your Electron app:
$ npm start
If you have followed instructions correctly so far, you should get a new window similar to this:
Open “index.css” file and add the code below to change the color of “Hello World !!” string.
#hworld {
color: red;}
Run the following command again to see CSS style applied to “Hello World !!” string.
$ npm start
You now have the bare minimum set of required files to run a basic Electron application.
You have “index.js” to write program logic, “index.html” for adding HTML markup and “index.css” for styling various elements.
You also have a “package.json” file and “node_modules” folder containing required dependencies and modules.
Package Electron Application
You can use Electron Forge to package your application, as recommended by the official Electron documentation.
Run the command below to add Electron Forge to your project:
$ npx @electron-forge/cli@latest import
You should see some output like this:
Checking your system
Initializing Git Repository
Writing modified package.json file
Installing dependencies
Writing modified package.json file
Fixing .gitignore
We have ATTEMPTED to convert your app to be in a format that electron-forge understands.
Thanks for using "electron-forge"!!!
Review “package.json” file and edit or remove entries from “makers” sections according to your needs.
For instance, if you don’t want to build an “RPM” file, remove entry related to building of “RPM” packages.
Run the following command to build the application package:
$ npm run make
You should get some output similar to this:
> helloworld@1.0.0 make /home/nit/HelloWorld> electron-forge make
Checking your system
Resolving Forge Config
We need to package your application before we can make it
Preparing to Package Application for arch: x64
Preparing native dependencies
Packaging Application
Making for the following targets: deb
Making for target: deb - On platform: linux - For arch: x64
I edited the “package.json” file to build only the “DEB” package.
You can find built packages in the “out” folder located inside your project directory.
Conclusion
Electron is great for creating cross-platform applications based on a single codebase with minor OS specific changes.
It does have some issues of its own, most important of them is resource consumption.
Since everything is rendered in a standalone browser and a new browser window is launched with every Electron app, these applications can be resource intensive compared to other applications using native OS specific application development toolkits.
Vue.js Template Introduction
Vue.js, which is used to build user interfaces (UIs) and single-page applications (SPAs), combines many of the best features of the JavaScript frameworks Angular and React, and many developers like to use Vue.js because it provides a neutral environment.
Like HTML, Vue.js has a template syntax, and we can use template syntax to bind the DOM with the components data.
In this article, we will show you how to insert data into the template syntax and the ways to interpolate different types of data.
Text Interpolation
If we want to bind a variable from the relative component instance, we can use double curly braces, which is also referred to as “mustache” syntax.
<p> {{ linuxhintText }} </p>
Vue.js offers two-way binding, which means that, whenever the value of a variable is changed, the element will be rendered again.
However, if we do not want it to be updated, we can use the v-once directive.
<p v-once> {{ linuxhintText }} </p>
Raw HTML Interpolation
Vue.js does not allow for the data binding of plain text, but we can bind raw HTML text using the v-html directive.
In the example below, we have a variable in a component called rawHTML that contains some raw HTML text.
data() {
return {
msg: "Hello Vue",
rawHTML: "<p> Linuxhint is <b>Great</b> </p>"
}}
We can bind the rawHTML variable using v-html directive as follows.
<template>
<h1>{{ msg }}</h1>
<div v-html="rawHTML"></div></template>
The div tag will have a p tag inside it.
Attributes Interpolation
In the raw HTML interpolation, we did not use double curly braces to bind the variable.
Therefore, if we want to bind a variable inside the HTML attribute, we can use the v-bind directive.
<div v-bind:class="container"></div>
Expressions
Vue.js does not only provide features for binding a variable.
Vue.js can be used to write various types of expressions within double curly braces.
{{ count + 1 }}{{ check ? "true" : "False" }}{{ arr.sort().reverse() }}
Wrapping Up
In this article, we introduced Vue.js’s simple yet useful template syntax.
However, there is a lot more to learn about Vue.js.
You can visit the official website of Vue.js here, and you can keep learning about JavaScript with linuxhint.com.
Install Vue.js in Ubuntu 20.04
In this tutorial, we will provide an easy step-by-step process to help you get started with Vue.js.
Vue.js is a powerful, progressive, reactive JavaScript framework that is approachable and easy to learn.
It provides many different tools and libraries that facilitate the application development process.
If you have knowledge of HTML, CSS, and JavaScript, you can start building web applications with Vue.js in no time.
Installation
To integrate Vue.js into a project, you can use the CDN package, NPM, or CLI.
Using the CDN Package
If you want to start learning Vue.js, then it is best to use the CDN package.
You can simply add the following script tag in your project to get started.
<script src="https://unpkg.com/vue@next"></script></td>
However, this method is not recommended for production purposes because it can lead to issues with compatibility in the future.
Using NPM
For large-scale production applications, you should install Vue.js using NPM.
To use this method, you must have Node.js installed on your machine.
If you have not installed Node.js yet, you can find out how by reading our article How to Install Node.js and npm on Ubuntu 20.04 – Linux Hint.
If you have already installed Node.js, then you can install Vue.js by running the following NPM command in your terminal
# latest stable
$ npm install vue@next
Using CLI
Vue CLI is a complete package for Vue.js development.
CLI is installed globally using the NPM package manager.
Before installing Vue.js using the Vue CLI method, you must have some prior knowledge of Node.js and front-end build tools.
In addition, we can use either npm or the yarn package manager.
$ sudo yarn global add @vue/cli# OR
$ sudo npm install -g @vue/cli
After installing the latest version of Vue.js using Vue CLI, you can easily upgrade your projects.
To check your version of Vue.js, you can run the following command
vue --version
If you want to upgrade to the latest stable version of Vue.js, you can use the following Vue CLI command.
$ sudo yarn global upgrade --latest @vue/cli# OR
$ sudo npm update -g @vue/cli
Getting started with Vue.js
To get started with Vue.js, to create a project using Vue CLI using the following command.
vue create demo-app
After running this command, you will be asked to choose a preset.
You can either go with the default or add custom features.
You can also use the GUI method to create a Vue project by using the following command.
vue ui
This command will open a window in the browser to help you create a project.
Summary
In this article, we showed you how to install Vue.js using three different methods.
After installing Vue.js, you can efficiently manage your web application.
If you want to start using Vue.js right away, you can use the CDN package method.
However, for production purposes, you should use either the NPM method or the CLI method.
To learn more about Vue.js, you can visit the official website here: Vue.js.
Javascript Form Validation
Form validation is the basic and most important part of the web development process.
Usually, form validation is done on the server-side.
Form validation helps in showing error messages to the user if there is any unnecessary or wrong data is provided, or a required field is left empty.
If the server finds any error, it throws back that error; then, we show the error message to the user.
But, we can use javascript at the front-end to validate the form data and show errors right away.
In this article, we will learn the basic form validation.
So, let’s get straight to the examples and see how can we do that.
Examples
First of all, we assume a form with the name of “testForm,” in which we have an input field with the label “User Name,” and an input type submits in our HTML file.
In the form tag, we have created an onsubmit event, in which we are making closure and returning a function validateFunc().
<form action="" method="get" name="testForm" onsubmit="return(validationFunc())">
<label for="name">User Name</label>
<input type="text" name="name"><br>
<input type="submit" value="Submit"></form>
In the script file, we will write the function definition of validateFunc(), which will get executed every time when the user hits the submit button.
In that function, we will validate the username input field.
We suppose that we want to validate either the username field is empty or not when the user hits the submit button.
So, to validate the username field.
We first assign a variable to the document.testForm, just to give a clean and understandable look to the code.
Then, in the function definition, we will write the code for validation.
We will write an if statement to check the empty form field.
If the username field is empty, we will show an alert box to show the error, focus on the username field again, and return false so that the form won’t get submitted.
Otherwise, if it passes the check and data get validated, we will return true to the function.
var theForm = document.testForm;// Form validation codefunction validationFunc() {if (theForm.name.value == "") {
alert( "name is empty" );
theForm.name.focus();
return false;}return (true);}
After writing all this code.
If we run the code and click on the submit button without writing anything in the form field.
As you can observe in the screenshot attached below, it throws an error in the alert box.
This is a very basic yet good example to get started with implementing the form validation.
For further implementation, like multiple form validations or you want to have a check on character length as well.
For that purpose, we first suppose two form fields in the form tag with the label of “email” and “password” in our HTML file.
<form action="" method="get" name="testForm" onsubmit="return(validationFunc())">
<label for="name">User Name</label>
<input type="text" name="name"><br>
<label for="email">Email</label>
<input type="email" name="email" id="><br>
<label for="password">Password</label>
<input type="password" name="password" id="><br><br>
<input type="submit" value="Submit"></form>
For validation, we will again put an if statement for validation of the email and password form fields in the function definition of the script file.
Suppose we want to apply multiple validations on the email field like the field should not be empty, and its length should not be less than 10 characters.
So, we can use OR “||” in the if statement.
If any of these errors occur, it will show an alert box with the error message that we want to show, focus on the email form field, and return false to the function.
Similarly, if we want to apply the character length check on the password field, we can do so.
var theForm = document.testForm;// Form validation codefunction validationFunc() {if (theForm.name.value == "") {
alert( "name is empty" );
theForm.name.focus();
return false;}if (theForm.email.value == "" || theForm.email.value.length < 10) {
alert( "Email is inappropriate" );
theForm.email.focus();
return false;}if (theForm.password.value.length < 6) {
alert( "Password must be 6 characters long" );
theForm.password.focus();
return false;}return (true);}
After writing all this code, reload the page to have updated code.
Now, either we leave an empty email field or write an email less than 10 characters.
In both cases, it will show an “Email is inappropriate” error.
So, this is how we can apply basic form validation.
We can also apply data validation on the client-side using Regex or by writing our own custom function.
Suppose we want to apply data validation on the email field.
The regex would be like this for validating an email.
if (/^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/.test(theForm.email.value)) {
alert( "Email is inappropriate" );
theForm.email.focus() ;
return false;}
This was just a basic demonstration of data validation using regex.
But, the sky is open for you to fly.
Conclusion
This article covers the basic form validation.
We have also tried and have a sneak into the data validation using regex.
If you want to learn more about regex, we have a dedicated article related to regex on linuxhint.com.
For learning and understanding javascript’s concepts and more useful content like this, keep visiting linuxhint.com.
Thank you!
Javascript Try Catch
Javascript is a translative programming language.
Just like any other language, a developer or programmer often needs to care about error handling.
Mostly a programmer or developer needs to handle errors while accessing or assigning some data to the database.
So, error handling is an essential part of any programming project.
There are three types of errors in programming that a programmer or developer often has to face.
Syntax Error– An error in writing code against the syntax of programming language.
For example, missing a semi-colon or not following the convention of creating and calling the function.
Logical Error– An error in the logic building.
For example, implementing the wrong arithmetic operation, which results in the wrong output.
Runtime Error– Error occurred during the runtime.
Like, calling a function without declaring it.
The error that we get during the runtime is also known as anexception.
Exceptional handling is very important.
Because we can’t throw the errors and error codes right away.
We have to handle that.
So, In this article, we are going to have an understanding of how to handle exceptions using javascript’s try-catch block.
We will also learn how to throw a custom message against an error and how to use the “finally” block with a try-catch block.
Syntax
The syntax for using a try-catch block is very simple and easy to use.
We can simply use the try-catch block like this
try {
//code to try or test
throw //throw a custom error to catch} catch (error) {
// code after getting an error } finally {
// code which executes in any case}
In this syntax, we first write some lines of code in the “try” block to test.
If that code gets executed or passed the test successfully.
The “try” block won’t throw any error to the “catch” block and execute the “finally” block.
Otherwise, it will throw an error to the “catch” block where we can handle the exceptions according to the given error.
We can throw a custom error to the “catch” block as well using the “throw” keyword.
“Finally” block will get executed in any case.
Either the “try” block throws any or not.
Let’s try a couple of examples to have a better understanding.
Examples
First of all, to demonstrate the simple and basic working of the try-catch block.
We try to call a function without declaring it anywhere.
addition()
It will definitely throw an error in the console
But, if we try to call it in a try block now
try {
addition()} catch (error) {}
It won’t show any error in the console anymore because we did not write any code in the catch block for error.
So, we can modify and console the error message in the catch block now.
try {
addition()} catch (error) {
console.log("Error Message => " + error)}
We can see our custom message in the console against the error.
So, this is the very basic usage of the try-catch block.
Now, let’s learn about throwing a custom error in the try block.
Throw
Suppose we want to throw a different custom error on the base of different errors while trying.
We can throw a custom error, that “Function definition doesn’t exist.” Like this
try {
throw new Error ("Function definition doesn't exist")} catch (err) {
console.log("Error Message => " + err)}
As you can see in the output, the error message is now changed to our custom error thrown.
ProTip
Suppose we try to apply this try-catch on an asynchronous function.
It won’t work.
Because the engine would have moved to the next line, execute the final block, and the asynchronous function would get executed later.
For example, if we apply the setTimeout Function inside a try-catch block.
try {
setTimeout(() => {
addition();
}, 3000)} catch (err) {
console.log("Error Message => " + err)} finally{
console.log("reached 'finally' block")}
You can observe that the “finally” block gets executed first, and the error is thrown later if we take a look at the error.
It is not the error from the catch block, but it is an original programming error, which means that the catch block doesn’t get executed because they try block didn’t find any error.
Alright! Now, if we want to make it work.
We have to apply the try-catch block inside the setTimeout function instead of outside.
So, the true way of implementing an asynchronous function with a try-catch block would be like this.
setTimeout(() => {
try {
addition();
} catch (err) {
console.log("Error Message => " + err)
} finally{
console.log("reached 'finally' block")
}}, 3000)
You can observe in the output that after the delay of 3 seconds because of the setTimeout function.
We have got the error message from the catch block first, and then the “finally” block gets executed.
Conclusion
In this article, We have learned to implement the try-catch block step by step in such an easy and profound way that any beginner after reading this article would be able to apply it anywhere he needs.
So, keep on learning and getting experience with linuxhint.com.
Thank you!
Javascript Random Number
While developing a gaming website, we often need to generate random numbers.
In this article, we are going to know how we can get a random using the random method.
The random method helps in generating pseudo-random numbers, since, arithmetically, generating a true random number is impossible.
Syntax
We can get random numbers using Math.random() function, like this:
Math.random();
This function doesn’t take any arguments and will return the random float number between 0 and 1.
If we want to generate random numbers between any two numbers or up to a limit.
The syntax would be different for them.
For better understanding, let’s try a couple of examples.
Examples
Suppose, we want to generate a random number from 0 to 99.
The syntax for providing a limit or a range is:
Math.random() * 100
Keep in mind that 100 is a limit or range, not the number.
You can see that it has generated a number from 0 to 99, but, it’s a float number.
So, if we want to have a whole number and not a float number, ,we can apply a Math.floor() method over Math.random() method, like this:
Math.floor(Math.random() * 100)
That looks great!
Now, what if we do not want to have numbers from 0 to 99 or onwards but from some other number, for example, 50 to 90.
First, let’s see how we can do that, and later we will see how it works.
Math.floor((Math.random() * 40) + 50)
In this syntax, 40 is the range or limit from 50 to onwards, 50 as the starting number.
In the end, if we want to build our custom random function to which we can provide two numbers (minimum and maximum) and get a random number between those two numbers.
The function would be like this:
function getRandomNum(sNum, lNum) {
return Math.floor((Math.random * (lNum - sNum)) + sNum)}
Keep in mind that the ending number or “lNum” will be excluded.
In case you want to include that as well add “1” in the range, like this:
function getRandomNum(sNum, lNum) {
return Math.floor((Math.random * (lNum - sNum + 1 )) + sNum)}
After writing this function.
Let’s call it and see the results.
getRandomNumber(20, 40);
As you can see, we are getting random numbers from 20 to 40.
So, these are some of the different ways to generate pseudo-random numbers using the Math.random() method.
Conclusion
In this article, we have learned to get random numbers and tried several techniques to get the desired results.
We have also learned to make a custom function in which we can provide the range of numbers and get the random numbers between that ranges.
So, keep on learning Javascript with linuxhint.com to have a better grasp over it.
Thank you!
JavaScript onClick
Introduction
JavaScript is a well-known programming language.
It is used in more than 95% of the websites we interact with daily.
You may often see that on the click of a button, a whole page gets changed, a form field is opened, or a pop-up box appears.
From the perspective of a programmer/developer, how can we implement such functionality and handle the website’s interactions with users? When it comes to interaction, JavaScript provides built-in functions to control events on a site.
There are two types of events:
Event Listener – listens and waits for the event to get fired
Event Handler – executed when an event is getting fired
In this article, you will learn about the most used event handler of JavaScript, the onClick event.
There are other event handlers for hovering over an element or for keyboard key presses, but in this article, we will focus on the onClick event.
The onClick event is used to perform certain tasks at the click of a button or by interacting with an HTML element.
We will now show you an example to demonstrate how the onClick event works.
Example: Change Text Using onClick
In this example, we will change a selection of text on the click of a button using the onClick event.
First, we will make a paragraph tag and give it an ID “paragraph” to access it later.
We will create a button with the onClick event and call the function named “change.”
<p id="paragraph">Linuxhint</p><button onclick="change()">Change!</button>
In the script file, we will create a flag variable that will allow us to check the status of the text in our HTML paragraph tag.
Then, we will write a function defining the “change” function.
In the function definition, we will create an “if” statement, in which we will check the status using the flag variable.
We will also change the text and alter the flag.
It is a pretty simple piece of code!
var a = 1;
function change(){
if (a==1) {
document.getElementById("paragraph").innerHTML = "Linuxhint is awesome"
a = 0;
} else {
document.getElementById("paragraph").innerHTML = "Linuxhint"
a = 1;
}}
All right! After writing all this code, we will run the code, move to our browser, and click the newly created button.
After clicking the button, the text should be changed from “Linuxhint” to “Linuxhint is awesome.”
We can apply the same technique anywhere to change the content of our website according to our needs.
We can use it in changing an image or performing any type of task that we can imagine with this tool.
Conclusion
This article explains how to use the onClick event.
In this article, you learned the concept of the onClick function in a practical way.
The usage of the onClick event is so simple, even a beginner can start working with this function.
You may continue learning, working, and gaining more experience at linuxhint.com to have a better grasp of this programming language.
Thank you so much!
JavaScript Cookie
JavaScript is the language behind almost every website you will use.
JavaScript is the language of the online world and is used in online communication, as well.
The concept and need for cookies arose when developers wanted to store user information in the browser to avoid overloaded communication over a stateless HTTP server.
A cookie is like a file containing some data that is stored on the user’s machine.
The information stays on the computer, even if the user closes the website or closes the browser.
This article provides an overview of the use of cookies.
Syntax
The syntax for creating and saving cookie is as follows:
document.cookie = "cookieName=cookieValue"
The cookie saves the data in key-value pairs.
Creating a Cookie
You can create a cookie by assigning a string to the document.cookie, for example, userName.
document.cookie="userName=John"
Getting a Cookie
Now, if we want to have a look at the Cookie, we can get the cookie by assigning document.cookie to a variable and then console it.
var cookieStat = document.cookie;
console.log(cookie.Stat);
Setting/Updating a Cookie
We can update a cookie as well using the same syntax we used for creating a cookie.
To add the expiry date in the cookie, for example, we will use the following technique:
var expiryDate = new Date();
expiryDate.setDate(expiryDate.getDate() + 1)
expiryDate.toUTCString()
document.cookie = "userName=John"
document.cookie = "expires=" + expiryDate.toUTCString()
After updating, take a look at the cookie:
console.log(document.cookie)
You can see that cookie is updated.
Deleting a Cookie
There is no built-in method or object for deleting a cookie in Python, but a cookie is deleted when it expires.
By assigning a past date to a cookie, you can delete it.
var expiryDate = new Date();
expiryDate.setDate(expiryDate.getDate() - 1)
expiryDate.toUTCString()
document.cookie = "userName=John"
document.cookie = "expires=" + expiryDate.toUTCString()
After assigning a past date, the cookie will no longer work and will self-delete by expiring.
Conclusion
So, this is how you can create a cookie, set or update a cookie, and delete a cookie.
In this article, you learned about cookie usage, including how cookies can help you in development and save necessary user data.
You can continue to learn more about JavaScript at linuxhint.com.
Thank you!
Javascript Refresh Page
Javascript is a widely-used programming language due to the expansion of the internet and the web.
In the modern world of the web, we can do almost every task in one single browser, and Javascript is used in every single website we see in our daily routine life.
Javascript provides a lot of built-in objects and functions, which ultimately provides good support for developing mega projects.
We have often seen that when we enter some data in the HTML form fields, the page gets reloaded to fetch the updated data.
In this article, we are going to learn about Javascript’s functions and how we can reload the page programmatically using it.
There are actually around 535 ways to reload a page.
Yes, 535 ways.
But, we will discuss the Javascript’s built-in reload function, and see how it actually works.
So, let’s get started!
Javascript’s built-in reload function is used to reload/refresh the current web page or specific area.
Syntax
The syntax for the reload function is:
location.reload();
This function doesn’t return any parameters.
But we can pass true or false.
In the case of true, the web page must have to be reloaded from the webserver.
Otherwise, for false, the web page is supposed to be reloaded from the cache of the web browser.
Let’s take a look at the examples and learn in a better way.
Examples
First, if we simply call the function.
It will definitely reload the page.
location.reload()
And if we pass true, it will reload the page from the webserver.
location.reload(true);
And if we pass false, it will reload the web page from the browser’s cache.
location.reload(false);
We can also reload the page using a function and the onclick event of a button.
First, create a button with the onclick event in the HTML file.
<button>Reload!</button>
And in the script file, the function should be like this.
function reloadPage(){
location.reload();}
So, this is a piece of very basic and still very profound knowledge about Javascript’s reloaded function.
Conclusion
In this article, we have learned about Javascript’s built-in reload function for reloading/refreshing the web page.
This video contains a detailed yet very simple and easy to understand the concept of Javascript’s built-in reload function.
So, keep on learning, working, and getting experience with linuxhint.com to have a better grasp over it.
Thank you so much.
Javascript Get URL
Being a javascript developer, we often need to get the URL of the current page to do some tasks according to our needs.
In this article, we are going to learn how we can get the current URL, know what its syntax is, and how we can extract different parts using the built-in window.location object.
The simplest and most straight forward way of getting the URL of the current page is shown below:
window.location.href
But, if we take a sneak peek into the window.location in the developer’s console, it is shown below:
We can observe what it has for us.
We could receive a good amount of information from the Window.location object.
For example:
Examples
If we want to get the protocol only, like HTTP or HTTPS, from the whole URL, we can get that using the very simple window.location.protocol, like the picture below:
window.location.protocol
And if we want to get the hostname from the URL, we can simply get that using the window.loation.host.
window.location.host
And similarly, if we want to get the pathname only, we can get that using window.location.pathname.
window.location.pathname
For getting the search query, we can use window.location.search.
window.location.search
So, these are basically some of the ways to get the current URL and extract some specific parts from it according to our requirements.
Moreover, window.location has a lot of other options for us.
Conclusion
In this article, we have learned about the window.location object, how we can use it to get the current URL, and extract some specific parts from that.
So, keep on learning, working, and getting experience with linuxhint.com to have a better grasp over it.
Thank you so much.
Javascript Print Page
Javascript is a scripting or programming language, which is most commonly used nowadays in the web industry.
It provides a lot of built-in objects, functions, and methods to perform several tasks.
In this article, we are going to have a look at one of them which is used to print the web page.
So, let us get started!
You must have encountered some websites that provide a button to print the whole web page, or you must have felt the need to print a web page but there is no print button there.
Javascript’s built-in object window provides us a method named print().
We can use window.print() function to fulfill this requirement.
Syntax
The syntax of the print function is:
window.print();
This simple syntax neither gets any parameters nor returns anything.
It simply fires the print window.
We simply have to make a button in our HTML, and on the on-click event of that button we can directly call the window.print() function.
<button onclick="window.print()">Print</button>
Then, on the web page, if we click the button, it will open up a window or dialog box, which we usually see while printing any document.
Be careful that it will print everything on the webpage.
Either that web page includes images or advertisements.
Conclusion
In this article, we have learned how we can print the whole web page, and the benefits and consequences of doing that.
This article explains the need and the usage of javascript’s built-in window.print() function.
So, keep on learning javascript’s concepts with linuxhint.com.
Javascript Alert
Javascript is the most known language of the web.
Javascript is widely used in front-end development as well as in the back-end.
Javascript provides a lot of built-in functions to help in development.
In this article, we are going to learn one of the javascript’s built-in alert() method, which is used to show pop-ups over the screen to either display a message or show a warning.
The alert box is different from any other message or text on the screen.
It is a pop-up that contains a message/text with an “OK” button.
The user won’t be able to do any task while an alert box is over the screen, and he/she clicks the “OK” button.
So, it is not recommended, if not needed.
So, let’s have a look at what is an alert box and what are the different ways to use it.
The alert() is basically a method, which is used to show a pop-up box over the web page.
Syntax
There are two different syntaxes for showing the alert box.
One of them is using the window’s object.
window.alert("Alert box from the linuxhint");
But, we can use the alert() method without the window’s object as well.
alert("Alert box from the linuxhint");
So, let’s try both of the syntaxes.
Examples
First, let’s try with the window’s object.
window.alert("Alert box from the linuxhint");
And now, without the window’s object.
alert("Alert box from the linuxhint");
You will witness that there is no difference in both of them.
The alert method doesn’t only take the string to show the message.
We can provide variable as well, and it worked perfectly fine,
var alertMessage = 'Alert Box using variable';
alert(alertMessage);
as you can see in the screenshot below that the message is displayed.
We have learned about providing a variable as well.
What if we want to show the pop-up alert box on the screen at the click of a button? For example, we have got some information from the user, and after successfully saving the user’s data on the server, we want to show a confirmation message that says “Added successfully”.
So, we can simply show an alert box like this.
<button onclick="alert(Added successfully)">Show Alert!</button>
Or, if we are getting a confirmation message from the server, and we want to show the message on the base of the message we got.
We can call the function on the button’s onclick method
<button onclick="alertFunc()">Show Alert!</button>
Then, later in the script, we can write the function in which we can show the alert message.
function alertFunc() {
var alertMessage = 'Alert Box using function';
alert(alertMessage);}
So, these are some of the different methods of using the alert() method.
Conclusion
In this article, we have learned about the javascript’s built-in alert method to show pop-up over the browser’s window.
This article has explained the use of the alert method in a very easy, profound, and effective way that any beginner can understand and use.
So, keep on learning, working, and getting experience with linuxhint.com to have a better grasp over it.
Thank you so much!
Javascript Map
In this article, we are going to learn one of the most widely used methods for the array, which is the map() method.
The map method helps in mapping arrays according to our requirements.
Let’s see, what is a map() method? What is the syntax for mapping arrays using the map() method?
The array’s map method is used to construct a new mapped array based on the return value of the callback function for each element.
var mappedArray = array.map(callbackFunction, thisValue)
The callback is the function that will be called every time for a single element and return a value that will be stored in a new array.
The syntax for the callback function is
function(value, [index[, array]])
value is a necessary argument, which is actually a single element of the array.
The index is an optional argument that will be used as the index of each element in the callback function.
The array is an optional argument as well.
We can pass this argument if we want to use the array in the callback function.
thisValue is the value we want to pass, which will be used as a “this” in the callback function.
Otherwise, “undefined” will be passed.
Javascript provides the for…in loop and foreach loop for iterating through elements and manipulating arrays.
But, why do we need a map method aside from that? There are two major reasons for that.
One is the separation of concern and the second is the easy syntax for doing such tasks.
So, let’s try some different examples to demonstrate the purpose and right use of it.
Examples
First of all, we are going to have a simple demonstration in which we have a simple array of numbers on which we will try to perform any simple arithmetic operation over every single element.
var arr = [4, 8, 16, 64, 49];
Now, before applying the map method over this array.
We will first write a callback function to which we can call in our map function in which, let’s say we want to multiply each element with 10 and have a new array.
function multiply(element){
var newElement = element * 10;
return newElement;}
Everything is set up to apply the map method over the array and have the results required.
var newArr = arr.map(multiply);
Now, if we have a look at the “newArr”,
console.log(newArr);
We can see the latest mapped array in the output as per our requirement.
Keep this in mind that the length of the new mapped array will definitely be equal to the original array.
There is a shorter way of doing the same task using the arrow or anonymous function within a map method.
So, we can write a callback function within a map method like this
var newArr = arr.map((element) => {
return element * 10})
Or, if we want to be a pro and make it more concise.
We can do this
var newArr = arr.map(e => e * 10)
Alright! So, this was the very basic demonstration of the map method and different ways to write the call back function.
But, this function comes more in handy, when we are playing with an array of objects.
That’s where it’s true implementation happens.
Using Map with an Array of objects
In this example, we suppose an array of objects in which each object contains the information of a player.
Player’s name and his ID.
var arr = [
{ id: 12, name: "James"},
{ id: 36, name: "Morgan"},
{ id: 66, name: "Jordan"}];
Now, let’s say we want to extract the IDs from each object and have a new array of IDs.
But, in order to understand, how the map method is different and helps better than the foreach loop.
We will try both of these(map method and foreach loop) to do the same task and learn the difference.
So, first, we will try to extract IDs using the foreach loop and then using the map method.
var extractedIDs = [];
arr.forEach((element) => {
return extractedIDs.push(element.id);})
Now, if we have a look at the extracted IDs.
console.log(extractedIDs);
We have got them separated in an array.
But, now let’s demonstrate the same output using the map method.
var extractedIDs = arr.map((element) => {
return element.id;})
console.log(extractedIDs);
By looking at the difference in code and the same output, we can realize the true difference between the two(foreach and map) methods.
The syntax and separation of concern.
Similarly, we can perform a lot of other operations.
If we have to play and get some data from the array of objects.
We suppose an array of objects in which each object contains two properties: first name and last name.
var arr = [
{ firstName: "John", lastName: "Doe"},
{ firstName: "Morgan", lastName: "Freeman"},
{ firstName: "Jordan", lastName: "Peterson"}];
Now, we want to have an array that contains the full names.
So, we will write a map function like this to fulfill our purpose
var fullName = arr.map((person) => {
return person.firstName + ' ' + person.lastName})
console.log(fullName);
As you can see, we have got a separate array with full names.
That’s great.
So, these are some of the basic and different ways of how a map function can be used to fulfill our development requirements and helps in every javascript developer’s life.
Conclusion
In this article, we have learned about javascript’s most used map() method for arrays and we have learned some of the different ways to use the map method.
This article explains the concept of the map method in such an easy and profound way that any beginner coder can understand it and utilize it to his needs.
So, keep on learning, working, and getting experience with linuxhint.com to have a better grasp over it.
Thank you so much!
Javascript Sort
As we have to manage arrays in almost all programming languages, JavaScript is no different.
Arrays are usually used to store data like strings, numbers, objects, and undefined.
With the exponential growth of online data, we frequently need to manage and sort the data.
Sorting is kind of a massive experience in almost every programming language.
It takes a lot of effort, machine power, and calculations to do the right sorting.
With the expansion of data, we need to sort and structure the data in a beautiful way.
Javascript provides a built-in array mutator method sort() for sorting arrays.
In this article, we will have a look at Javascript’s built-in sort() method and learn what the Javascript sort method is, as well as how we can use it for our purpose to sort elements in an array.
Let’s go ahead and start working!
The sort method is used to arrange different elements in an array in a specific order.
Syntax
The general syntax for the sort method is:
array.sort();
This method returns the sorted array in ascending order by default.
We would discuss a couple of examples to understand the sort method.
Examples
We suppose an array of string in which we have some different names of Linux operating systems.
let arr = ["Ubuntu", "Fedora", "CentOS", "Debian", "Kali Linux"]
Now, if we apply the sort method over this array:
arr.sort();
It will definitely sort the array in alphabetical order.
We can see the output in the screenshot below.
But, if we want to get the string in reverse/descending order.
We can apply a Javascript’s built-in reverse function over the sorted array like this:
var sortedArray = arr.sort();
sortedArray.reverse();
The shorter way to do the reverse is:
arr.sort().reverse();
Alright! It worked fine for the string.
Let’s try if it works for the numbers as well.
So, we first suppose an array of numbers.
let arr = [14,8,33,27,6]
Then apply the sort method over the array of numbers.
arr.sort();
It seems like it didn’t work well as it did for the string.
Because the sort method first converts the numbers into the strings and then sorts on the base of Unicode.
Although, “8” comes before “14” in numerical order.
But, in UTF-16 code units order, “14” comes before “8”.
The good thing, we got the solution for this.
CompareFunction
Here comes the concept of compare function that comes in handy in helping sort the numbers.
We can use a compare function to the sort method as a callback function, which takes two elements.
It then sorts them according to our requirement in the compare function and returns them to the sort method, continuously doing this until it reaches the end of the array.
The syntax for the sort method with the compareFunction would be like this:
array.sort(compareFunction);
Now, if we take a look at the technical details of the compareFunction, that is how it actually works.
If we do not provide a compareFunction to the sort method, it will sort according to the UTF-16 code unit orders.
If we utilize the compareFunction, all elements would be sorted in accordance with the return value of compareFunction.
So, if we want to write a compare function for the numbers.
That would be just like this:
function (a, b) { return a - b }
CompareFunction takes two values at a time and returns three types of values.
True or “1”, if the first value comes before the second value or the first value is greater than the second value:
False or “-1”, if the first value comes after the second value or the first value is greater than the second value.
And “0”, if two values are equal.
Now, if we try to apply it to sort the array of numbers.
We can apply it like this:
arr.sort(function (a ,b){ return a - b })
As you can see in the output, array having numbers have been sorted decently.
The shorter way of doing the same task will be like this:
arr.sort((a, b) => a - b)
But, this works only for the comparison of the numbers.
We can also use the sort method to sort the array of objects depending on the values of the object, which we want to sort the array of objects.
If suppose we would want to sort on the base of the number of users an array of objects in which every object includes the Linux Operating Systems and the number of their users, then we will be using the following:
arr = [
{name:"Ubuntu", users:3000}
{name:"Fedora", users:1500}
{name:"CentOS", users:2000}
{name:"Debian", users:5000}
{name:"Kali Linux", users:4000}]
So, in order to sort on the base of users.
The sort function would be like this:
arr.sort(() => { return a.users - b.users })
So, these are the different ways of using the sort method to sort the arrays of any type.
Conclusion
In this article, we have learned how we can sort an array of different types using Javascript’s built-in sort function.
This article explains the concept of the sort function from novice to intermediate level in a very easy, profound, and effective way.
So, keep on learning, working, and getting experience with linuxhint.com to have a better grasp over it.
Thank you so much.
Applying JavaScript’s setTimeout Method
With the evolution of the internet, JavaScript has grown in popularity as a programming language due to its many useful methods.
For example, many websites use JavaScript’s built-in setTimeout method to delay tasks.
The setTimeout method has many use cases, and it can be used for animations, notifications, and functional execution delays.Because JavaScript is a single-threaded, translative language, we can perform only one task at a time.
However, by using call stacks, we can delay the execution of code using the setTimeout method.
In this article, we are going to introduce the setTimeout method and discuss how we can use it to improve our code.
The setTimeout method is a built-in method that takes a callback function as an argument and executes it after a given amount of time.
The syntax for the setTimeout method is as follows:
setTimeout(callbackFunction, delay, arguments...)
The callbackFunction is the function we want to execute after a given amount of time; the delay is the time in milliseconds after which we want to execute the callback function; and the arguments are other parameters we want to pass to the callback function.
Now, we will apply the setTimeout method.
First, we define a function called linuxhintFunc that prints the string “Hello from Linuxhint.”
function linuxhintFunc() {
console.log("Hello from Linuxhint.");}
Next, we call linuxhintFunc in setTimeout and provide a time delay of 2000 ms (2 s).
setTimeout(linuxhintFunc, 2000)
Once the web page is loaded, there is a delay of 2 s before the function is called.
We can perform the same task using the arrow function or an anonymous function.
setTimeout(() => {
console.log("Hello from the Linuxhint");}, 2000)
Again, there is a delay of 2 s.
Note: The setTimeout method is an asynchronous method, which means that, although JavaScript is a single-threaded language, this function runs on a different thread.
The setTimeout method places the function in the queue of the call stack and waits until the call stack is free.
If we try to print a message or run a function in setTimeout without a delay, then this action would be jump to the front of the queue first and run when the setTimeout method is executed.
console.log("Hello from the Linuxhint-1")
setTimeout(() => {
console.log("Hello from the Linuxhint-2")}, 0)
console.log("Hello from the Linuxhint-3")
Looking at the output, the order of the output is not the same as that of the input.
Therefore, the setTimeout function can delay the execution of code.
Conclusion
This article introduces JavaScript’s built-in setTimeout method and discussed how we can use it.
We hope that you learned something from this article and that you continue learning about JavaScript with linuxhint.com.
How to Get Current Date & Time?
Javascript has become a massively used programming language due to the expansion of the internet and the web at an unbelievable pace.
In the modern world of the web, we can do almost every task in one single browser, and Javascript is used in every single website we see in our daily routine life.
We frequently used to see the date and time at almost every website.
In this article, we are going to have a look at how we can get the current time and what are the different ways to get the date and time according to our requirement.
Javascript provides a built-in object Date, which helps in managing all the date and time.
Later, we can extract whatever we want according to our needs using different built-in methods.
So, let’s just straight jump into the process and learn the different techniques to extract the current date and time.
First of all, we will create a new object of Date() and declare a variable named “current” and assign the new Object of Date() to a “current” variable.
var current = new Date();
After assigning, let’s have a look at the object Date what does it have for us.
console.log(current)
Alright! It looks pretty cool in a good format.
But, how about if we want to get only the year from the entire date? We can use the built-in function getFullYear() for getting the year only.
current.getFullYear();
Similarly, if we want to extract only the year, we can use the built-in function getMonths() for getting the month only.
current.getMonth();
There seems like an issue.
This is not the 8th month(August)! As we can see in the above complete output for the new Date object.
This is September.
Well, this is because of the digital(0-11).
So, we have to add “1” to it for getting the right month every time.
current.getMonth() + 1;
This is fine now.
Just like for the year, we can do the same for the date.
For example, to extract or get only the date, we can use the built-in function getDate().
current.getDate();
Just like a date, we have built-in functions for extracting the desired piece of time.
For example, if we want to get or extract the hours only, from the whole current time, we can use the built-in function getHours().
current.getHours();
The same goes for the minutes.
To extract minutes only, we can use getMinutes().
current.getMinutes();
To extract seconds only, we can use getSeconds().
current.getSeconds();
Advanced built-in functions
Here we have some advanced built-in functions to get the date and time in a pretty clean and good formatted string.
For example, in order to get only the time, not the date, in the form of string we can use the built-in function toLocaleTimeString() to our purpose.
current.toLocaleTimeString(); // "2:42:07 PM"
And, if we want to extract only the time in the form of string.
We can use the built-in function toLocaleDateString().
current.toLocaleDateString(); // "9/29/2020"
And, if we want to extract both the date and time in a single string, we can use the built-in function toLocaleString().
current.toLocaleString(); // "9/29/2020, 2:42:07 PM"
So, this is how we can get the date and time using the built-in date object and extract the required months, years, or minutes using different methods.
Conclusion
This article explains how we can get the current date and time and how we can use it to our needs in a very easy, profound, and effective way that any beginner can understand and use.
So, keep on learning, working, and getting experience with linuxhint.com to have a better grasp over it.
Thank you so much!
Javascript Confirm Method
Javascript is the most known language of the web.
Javascript is widely used in front-end development as well as in the back-end.
Javascript provides a lot of built-in objects, functions, and methods to help in web development.
In this article, we are going to learn one of the javascript’s built-in confirm() method, which is used to show pop-ups over the screen and get the user’s response.
The confirm box is a bit different if we try to compare it with the alert box.
It is a pop-up that contains a message/text with two buttons, “OK” and “Cancel”.
The user won’t be able to do any task while a confirm box is over the screen, and he/she clicks the “OK” or “Cancel” button.
This is the reason behind not recommending it’s often used.
So, let’s have a look at what is a confirm box and what are the different ways to use it.
The confirm() is basically a method, which is used to show a pop-up box over the web page, and it contains a message or text and two buttons, “OK” & “Cancel”.
On the click of the “OK” button, the confirm method returns “true”.
Similarly, on the click of the “Cancel” button, it returns false.
Syntax
There are two different syntaxes for showing the confirm box.
One of them is using the window’s object
window.confirm(message);
But, we can use the confirm() method without the window’s object as well.
confirm(message);
In this syntax, the message can be any string or a variable that can include a message.
So, let’s try both of the syntaxes.
Examples
First, let’s try with the window’s object
window.confirm("Confirm message from Linuxhint");
And now without window’s object
confirm("Confirm message from Linuxhint");
You will witness that there is no difference in both of them.
The confirm method doesn’t only take the string to show the message.
We can provide variable as well, and it worked perfectly fine.
var confirmMessage = Confirm Message using variable';
confirm(confirmMessage);
As you can see in the screenshot below that the message is displayed.
We have learned about providing a variable as well.
What if we want to show the pop-up alert box on the screen at the click of a button.
For example, we have got some information from the user, and after successfully saving the user’s data on the server, we want to show a confirmation message that “Confirmed”.
So, we can simply show a confirmation box like this.
<button>Show Confirm Box!</button>
Or if we are getting a confirmation message from the server, and we want to show the message on the base of the message we got.
We can call the function on the button’s onClick method.
<button>Show Confirm Box!</button>
And later in the script, we can write the function in which we can show the confirmation message.
function confirmFunc() {
var confirmMessage = 'Confirm Box using function';
confirm(confirmMessage);}
So, these are some of the different methods of using the confirm() method.
Conclusion
In this article, we have learned about the javascript’s built-in confirm method to show pop-up over the browser’s window.
This article has explained the use of the confirm method in a very easy, profound, and effective way that any beginner can understand it and use it.
So, keep on learning, working, and getting experience with linuxhint.com to have a better grasp over it.
Thank you so much.
Applying JavaScript’s Splice Function
JavaScript is a lightweight programming language, and as with any programming language, when developing JavaScript programs, we often need to work with arrays to store data.
In this article, we will introduce JavaScript’s built-in splice function and discuss how we can use it to manipulate an array.
As data are generated, the structures used for storage must be updated.
For this reason, a programmer must often add elements to or remove elements from an array.
The splice function is used to add elements to or remove elements from an array at a given index, and it returns the elements removed from the array.
The syntax for the splice function is as follows:
array.splice(index, removeCount, items...)
Here, index is the position at which we want to add or remove elements, removeCount, which is an optional argument, is the number of elements that we want to remove, and items, which is also optional, contains the elements we want to add.
Now, we will go over a few examples to show how the splice function is implemented.
First, suppose we have an array that consists of five elements.
let arr = [10,20,30,40,50]
To remove the elements 20 and 30 (at position 1 and position 2 in the array, respectively) from the array, we simply call the splice function and tell it to start from the first index and remove 2 elements.
arr.splice(1,2);
The values 20 and 30 are returned as the output.
Next, we can look at the original array with the following command:
console.log(arr);
The two elements returned in the output are no longer in the array.
Next, we will add elements to the array using the splice function.
Because we will not remove elements from the array, we can provide a value of zero for removeCount and then provide the elements we want to add.
arr.splice(2, 0, 30, 35);
The above command returns an empty array because no elements were removed.
However, if we look at the original array, we can see that it has been updated.
console.log(arr);
The values 30 and 35 were successfully added at the second index.
Finally, if we want to remove elements and add elements, we can provide values for both removeCount and items.
arr.splice(1, 2, 15, 20, 25);
The above command has returned the two elements that were removed, and if we print the original array to the console, we can see that 20 and 30 are no longer in the array and that 15, 20 and 25 have been added.
console.log(arr);
Conclusion
In this article, we discussed several ways to use the splice function to update arrays.
We hope you found this article useful and continue to learn JavaScript with linuxhint.com.
Javascript Trim String
Javascript is a scripting or programming language, which is used both on the client-side and back-end of the web.
Just like any other language, strings are an important type of the variables, and we often need to manipulate or alter strings as per our needs.
While getting data from the user in the form fields, a programmer has to take care of a lot of things.
In this article, we will have a look at javascript’s trim() function.
We will learn how this function helps in beautifying the strings and how can we get rid of extra spaces.
So, let’s take a look at what is a string and how we can trim the strings.
The string is a simple text or characters which can include the alphabets, numbers, or symbols.
Javascript’s trim() method trims the extra white space from both sides of the strings.
Extra white space can be space or tab, etc.
Syntax
Syntax for the trim() method is as follows:
string.trim();
In javascript’s trim string method, we simply call the function over a string, and it trims the string into a clean, space free string.
This function doesn’t take any arguments.
Let’s try some examples and understand it.
Examples
First, we suppose a string and add some extra white space around the string.
let str = " Linuxhint! "
Now, to get rid of the extra white spaces from both sides, we try to apply the trim() method over that string and see how it works.
str.trim();
We can see in the output that the string is trimmed and there is no extra whitespace left around the string as we desired it to happen.
Now, a question arises: what if we want to trim the string from only the left side or the start of the string and vice versa.
There is a built-in function for that as well.
There are two different trimStart() and trimLeft() functions, but these both do the same task.
So, if we want to trim the string from the left side only and want to keep the whitespaces on the right side.
We can use the trimStart() or trimtrimLeft() function.
str.trimStart();
str.trimLeft();
As you can see that both functions do the same task and trim the strings from the left side only.
Similarly, if we want to trim the string from the last or the right side only.
We can use any of the trimEnd() or trimRight() functions.
str.trimEnd();
str.trimRight();
It is observed that the string is trimmed only from the right side, as we expected.
So, this is how the javascript’s built-in functions trim(), trimStart(), trimLeft(), trimEnd() and trimRight() works and helps us in getting rid of the extra whitespace around the string.
Conclusion
In this article, we have learned about javascript’s built-in string trim() function and see it’s various implementations.
We have also learned about the trimStart() and trimEnd() functions.
This article includes profound and explained in-depth knowledge, the need, and the usage of the javascript’s string trim function.
So, keep on learning javascript with linuxhint.com.
JavaScript Sleep Function
Javascript is the language of freedom yet is a function-oriented language at the same time.
Unlike other languages, javascript does not provide a built-in sleep() function.
You can either build a custom sleep() function using the built-in setTimeout() function, or the latest ECMAScript promises an async-await function.
This article shows you how to stop or pause the execution of the sleep function for a desired amount of time using promises or async-await functions.
Before Starting
Before you start to build a sleep function, you need to understand that the setTimeout() function does not work if you expect it to stop the execution.
Many programmers and developers try to use the function with loops but fail because the setTimeout() function is used to wait for some given amount of time and then runs the given function.
You can, however, use the setTimeout() function to build a sleep function using promise if your purpose is to stop the execution for a desired amount of time.
Using the Sleep Function
So, we will make a custom sleep function in which the function will get time in milliseconds as an argument and return a promise.
The promise will include a setTimeout() function, which will pass the resolver as a function and time in milliseconds to the setTimeout() function.
So, in the end, the sleep function should look like this:
function sleep(ms){
return new Promise( resolver => setTimeout(resolver, ms));};
And now, wherever you want to use this sleep function, you can easily use it.
Now, we will use this sleep function in a couple of examples to show you how to use it in practice.
First, we will try to console some text and call the sleep function.
Since the sleep function is returning a promise, we put a then function after it, in which we will console some text and pass the argument ‘5000’ to the sleep function.
After running the program, you will see in the console that it will sleep for 5 seconds.
console.log("Sleep function will wait for 10 seconds and then it will print 'Done'");
sleep(5000).then(()=>{
console.log("Done");})
You can witness the delay of 5 seconds to get to the “Done” status in the console.
Suppose we want to perform an animation after every 2 seconds.
To do so, we will simply write an asynchronous animation function, in which we will animate something, stop the execution for 2 seconds using sleep, and then repeat this process using a for loop for 10 times.
async function animation(ms){
console.log("starting...");
for (let i = 0; i < 10; i++) {
console.log("animation after 2 seconds...")
await sleep(ms)}
console.log("This is the end.");}
After writing the asynchronous animation function, we can now call the animation function.
animation(2000);
After running the code, you will see in the console that the text “animation after 2 seconds” is repeating every two seconds.
Conclusion
This article showed you how to make a custom sleep function, alongside multiple demonstrations.
I hope this article has helped you to better understand the usage of sleep function.
You can learn more about Javascript at linuxhint.com.
Javascript Redirect
Javascript is a web-oriented programming language.
When using the web, you will often need to navigate through pages.
When you click on any button, submit a form, or log in to any website, you get redirected to a different new page.
Page redirection is an essential part of any website, but it is not only restricted to page navigation on a website.
There can be multiple reasons to redirect the page, for example:
The old domain name is changed to a new domain
Submission and Authorization of a form
On the base of the browser or language of the user
Redirect from HTTP to HTTPS
This article explains a few different ways to redirect a page.
Syntax
The syntax for navigating to a page using javascript is as follows:
window.location.href = "url"
In this method, you simply provide the URL to which you want to redirect the user.
The syntax for another method of redirecting a user to a new URL is as follows:
window.location.replace("url") // or
window.location.assign("url")
In this functional syntax, you provide the URL to which you want to redirect, and whenever this function is called, you will be redirected to that specific URL.
Here, “replace” and “assign” do the same task but with a subtle difference.
They both redirect to a new URL, but “replace” does not take the record of history and the user cannot go back to the old URL or previous page.
Meanwhile, “assign” keeps the history record and allows the user to go back to the previous page.
We will now look at some examples of both syntaxes.
Examples
First, we will create an on-click function on a button.
<button onclick="redirectFunction()">Linuxhint</button>
This function will redirect the user to the website “https://www.linuxhint.com.”
function redirectFunction() {
window.location.href = "https://www.linuxhint.com"}
Now, if the user clicks on the button, they will be redirected to linuxhint.com
In this next example, say, you want to redirect the user from an old domain to the new domain.
For testing purposes, suppose the current address is the localhost, but whenever the user enters the URL of the localhost, the user gets redirected from the localhost to the new URL, which is linuxhint.com in this example.
This is easier to do than you may think.
To do this, simply use the syntax of the second redirect method:
window.location.replace("https://www.linuxhint.com")
Now, if the user enters the localhost URL, they will be redirected to linuxhint.com.
But, if you look at the top-left button of the browser for going back to the previous page:
the button is dulled and the browser is not allowing us to go back to the previous page.
However, if you want to keep this option for the user, you can use “assign” instead of “replace.”
window.location.assign("https://www.linuxhint.com")
And now, if you look at the top-left button of the browser for going back to the previous page:
The button is not dulled.
You can go back to the previous page.
It is recommended to use “replace” instead of “assign,” here, because the purpose of redirecting to a new URL is that the old URL is not working or not available anymore.
Conclusion
This article explained a few different methods of redirection, along with real-life examples using these methods.
In this article, you have learned how to navigate to a new page and how to redirect from the old URL to a new URL.
You can learn more about javascript at linuxhint.com.
Joining Arrays
In JavaScript, as in many other scripting and programming languages, we often need to use arrays.
Furthermore, it is often useful to combine the elements of an array into a single string.
In PHP, for example, the implode function is used to join the elements of an array.
In this context, “implode” can be viewed as a synonym for “join”., however, there is no “implode” function; instead, there is a built-in “join” function that performs the same task.
In this article, we are going to examine JavaScript’s join function in some detail.
Syntax
The join function concatenates the elements of an array into a single string.
The syntax for the join function is as follows:
array.join(separator)
Here, separator is the string or string used to separate elements of the array; it can be any character or string, such as the space character (i.e., “ ”) or a string like “xyz”, but a comma is used as the default.
Examples
Now, let’s look at some examples.
First, we declare an array of letters.
let arr = ["a", "b", "c", "d", "f"]
We can call the join function for this array without providing a separator as follows, which will return the all characters from the array separated by commas:
Now, let’s see what will happen if we provide the space character as a separator:
Here, in the string returned, the array elements are separated by the space character instead of a comma.
We can provide any character or string as a separator.
If we want to put “ and ” between the array’s elements, we can do that as follows:
Here, every alphabet is separated by the “ and ”, which might be very useful for certain applications.
Any string can be provided as a separator for joining an array’s elements in the same way.
Conclusion
This article explains JavaScript’s join function and provides some useful examples.
We can provide any string we want as a separator to join an array’s elements.
We hope you found this article useful and continue using linuxhint.com to learn about JavaScript.
Global Variables
JavaScript is a versatile yet functional language.
Variables, which are key to any programming language, can be used to store values that can be accessed at any time.
However, when using functions, there are certain factors related to the scope of the function that limit our ability to access a variable.
We cannot access a variable if it is outside the scope of the function, and so the variables we want to use must have the proper scope upon declaration.
To avoid issues related to scope, it is important to understand global variables.
Therefore, in this article, we are going to discuss global variables and scope.
The scope of a function can be considered as a boundary within which the function can be accessed.
However, while a function does not know what is happening beyond the curly brackets that define it, a global variable can be accessed from anywhere in the program.
Syntax
The syntax used to create a global variable, shown below, is no different than that used to create other variables.
var variableName = value
However, the location of this declaration is very important.
We will explore this concept more fully by considering some examples.
Example
First, let’s create a function called subtraction.
function subtraction(a,b) {
var subNum = 23;}
In this function, we initialized a variable and assigned it a value.
Now, we can try to access the variable in another function, i.e., division, and call that function.
function division(a,b) {
console.log(subNum);}
division();
However, we get the following reference error because the variable subName is not defined within the correct scope.
This error will occur any time we try to access subNum outside the function in which it is defined.
For example:
function subtraction(a,b) {
var subNum = 23;};
console.log(subNum);
Here, we still cannot access the variable because it is restricted to the subtraction function.
However, let’s see what happens if we create the variable outside the function—for example, at the beginning of the script:
var globalVar = 11;
Now, let’s try to access it:
console.log(globalVar);
As shown below, we no longer get a reference error.
Furthermore, globalVar should be accessible from any function.
function division(a,b) {
console.log(globalVar);}
division();
As you can see below, globalVar is still accessible.
Conclusion
In this article, we explained scope and global variables by using simple examples.
We hope you continue learning JavaScript with linuxhint.com.
The Javascript for…in Loop
Javascript is one of the most popular programming languages in the world.
In any programming language, loops have an essential value.
Like many other languages, Javascript provides different loop syntax formats, as well.
This article discusses an important Javascript topic known as the for…in loop.
Sometimes, we may have to iterate through every single element of an object/array.
But, we do not usually know the length of that particular object/array.
The for…in loop even comes in handy when working with JSON.
In this article, we will take a look at the for…in loop, its syntax, and some examples using this loop.
Javascript’s for…in loop iterates through each property of the object.
Syntax
The syntax of the for…in loop is as follows:
for (const key in object) {
// body of the for...in loop}
where,
The key is the variable used in each iteration.
The object is the required object from which to iterate the loop.
Next, we will go over some examples to reinforce the concept and show you how the process works.
Examples
First, we see the simplest implementation of the for…in loop.
In this example, we will first assume an object:
let obj = {
firstName: "John",
lastName: "Doe"}
And then, we will iterate through the object and console each property using the for…in loop.
for (const name in obj) {
console.log(name + " = " + obj[name]);}
As you can see, the for…in loop has iterated through each property of the obj object and printed each property in the console, as we desired.
Javascript also provides the built-in hasOwnProperty() function.
We can perform the hasOwnProperty() check before performing any task in the for…in loop, like this:
for (const name in obj) {
if (obj.hasOwnProperty(name)) {
console.log(name + " = " + obj[name]);
}}
This function comes in handy when you need to use JSON or for debugging purposes.
When you do not know whether the key holds certain properties, you can also use the for…in syntax for the arrays, as well as for the strings.
let arr = [23,24,25]for (const value in arr) {
console.log(value + " = " + arr[value]);}
Similarly, you can apply this syntax to the strings, as well.
let str = "Linuxhint"for (const char in str) {
console.log(char + " = " + str[char]);}
But, it is not recommended to use the for…in loop for arrays and strings because there are dedicated loops and functions for arrays and strings.
Like, for…of or Array.protptype.forEach() is for the arrays for doing the same tasks in better ways.
Conclusion
In this article, you learned how the for…in loop works and how it helps with JSON and debugging.
You also learned how to use the for…in loop with arrays and strings, although this loop is dedicated to and recommended for objects.
But, I hope this article proved helpful to your understanding of the for…in loop and its various implementations.
To learn more about Javascript, you can find more articles at linuxhint.com.
Javascript Regular Expression
Many programmers are familiar with the notion that the regular expression is a useful yet underrated concept.
But, they do not know very well how to use regular expressions efficiently.
Regular expressions are used in not only Javascript but almost all other programming languages.
In this article, you will learn about regular expressions step by step.
It should be easy for programmers of any level to understand the concepts covered in this article.
A Regular Expression is an object in which patterns are given to match with the desired string.
Syntax
The syntax for a regular expression is very simple, and can be written as follows:
/pattern/flags
A pattern is a string in which you provide a pattern to match another string.Flags are optional attributes that serve varied purposes.
For example, the flag “g” stands for “global,” among many others.
The scope of regular expressions is very broad.
We will show you the basic ones that are most necessary for programming through a step-by-step explanation and some real-life examples.
There are a lot of methods in which you may need to use regular expressions, for example,’s search(), replace(), match(), and split() methods.
We will start with a simple string search without using the regular expression, and later, we will show you how to perform the same search using regular expressions.
Examples
We will first suppose the string:
let str = "Linuxhint is great.
linuxhint is working great and performing 100%."
We have repeated the same word “great” and “linuxhint” in the phrase.
The purpose of this weird string will become obvious in a moment.
Alright! Now, we will simply write the Javascript search string method to search for the term “work”
str.search("work");
As you can see, it shows the index from where the given substring “work” began.
Now, we will move on and try doing the same thing with the regex syntax.
Step 1: Search and Replace a Substring
You can search for a matching string using a regular expression by simply placing the substring between the two slashes in the expression.
str.search(/work/);
As you can see, it has also given us the same output.
Alright! Now, we will see what we can do with the regular expression.
Let us try to replace the word “great” with, say, “awesome” using the replace() method.
str.replace("great", "awesome");
Here, you can see the problem: the first occurrence of “great” has been replaced, but the second one has not.
In the first step, you simply learned how to search for a string using a regular expression.
Now, we will move towards the next step and learn about the concept of flags.
Step 2: Flags
In this step, you will learn more about the concept and purpose of flags in regular expressions.
We will use Javascript’s replace method to explain this idea.
If you want to replace all the occurrences of “great,” you can use the regular expression with the ‘g’ flag, which is short for global.
str.replace(/great/g, "awesome");
Perfect, all the occurrences of “great” are now changed.
But, you may face a problem if you try to change all the occurrences of “linuxhint” to, say, “our website” using the same technique.
We will try to do that first, then we will see how can we resolve this issue.
str.replace(/linuxhint/g, "our website");
Although we have provided the global flag with the regular expression, the first occurrence does not change.
This is because of case-sensitivity.
So, we will also need to provide the case-insensitivity flag ‘i,’ in this case.
You can do this simply by adding the ‘i’ flag along with the ‘g’ flag.
str.replace(/linuxhint/gi, "our website");
Great.
As you can see, all occurrences of the term “linuxhint” have been changed to the term “our website,” regardless of the case-sensitivity.
Similarly, you can use regular expressions’s split() function.
str.split(/linuxhint/gi);
Alright! The function worked fine.
The split() method has returned the array of substrings, based on the “linuxhint” term.
But, if you want to include the separators, as well, in the array of the substring, you will have to play with the patterns.
So, in this step, we have learned about the flags and how they help us.
There are more flags available.
For example, “m” is for multiline matching, “s” is for dot all, etc.
Now, we will move on to the concept of patterns and learn how to use these items.
Step 3: Patterns
In this step, you will learn how to utilize the patterns and related options.
To include the separators in the array of the substring, simply add parentheses around the pattern, as can be seen in the following image:
str.split(/(linuxhint)/gi);
Perfect! As you can see, the separators are also included in the array of substrings.
To split the base of two separators, you can give multiple substrings in a regular expression using the OR “|” operator.
str.split(/linuxhint|great/gi);
All right! The operator worked great, as we expect it to split.
Backslash
Now, to split between the base of the space “ “ or the dot “.” meaning to add special characters in the regular expression, add a backslash “\” before any special characters.
str.split(/\ |\./gi);
Okay, so far, so good.
For example, say, you want to change the dots into commas in the following expression:
str.replace(/\./g, ",");
It worked!
Backslashes are also used for another purpose.
To search any word, digit, or space, you can use \w, \d, and \s, respectively.
For example, to replace spaces with dashes, the following expression is used:
str.replace(/\s/g, "-");
Awesome! You can really see the potential in regular expressions, now.
Square Brackets [ ]
If you want to replace multiple characters in a string, you can provide all of them in a single square bracket, and they will be replaced by the given substring.
For example, if you want to replace three letters in a string and you do not want to put a lot of OR “|” operators in the regular expression, you can use square bracket syntax, in which you can give multiple letters, like this:
str.replace(/[nia]/g, "u");
You can even give a range of letters, like this:
str.replace(/[g-l]/g, "u");
Or, a range of numbers:
str.replace(/[0-5]/g, "9");
And, if you want to exclude the provided characters in the square brackets, you can use the caret character, like this:
str.replace(/[^g-l]/g, "t");
This comes in handy when getting data from users and testing and validating that data, especially in email, phone, or date validation.
Conclusion
This article has just scratched the surface of the Javascript regular expression.
It covers the concepts only from the beginner to the intermediate level.
There is a lot more to learn about the regular expression, and you can use this expression to do a lot of things that you may have not even thought of.
To keep on learning, working, and getting more experience, check out more articles on this topic at linuxhint.com.
Javascript String Length
Javascript is a scripting or programming language that is quickly becoming one of the most widely used programming languages in the world.
Strings are a crucial part of all programming languages.
Programmers often need to use strings to manipulate or manage data.
Javascript’s built-in functions or properties for manipulating strings can come in handy.
For example, if you are getting some user data in form fields in HTML and you want to restrict the length of a string while showing some data on a webpage, Javascript’s built-in string length property can help you in this case.
This article shows you what the string length property is and how you can use it in a few different scenarios.
The string length property fetches all the characters included within a string.
Syntax
The syntax for the string length is as follows:
string.length
This property simply gives back the total characters available in the string at run time.
Let us try out a couple of examples that use the string length property.
Examples
First, you will see the basic implementation of this property.
Later, you will see its application.
Suppose you have the following string:
let str = "Linuxhint is great."
If you want to know the number of characters in this string, simply apply the string length property as follows:
str.length
As you can see, this simply returns the length of the specified string.
You can use this property in multiple places.
For example, say you are doing a check-in on an “IF” statement, like the one below:
if (str.length <= 20) {
console.log("It's a short string");} else {
console.log("It's a long string");}
And, as you can see in the console output, the statement “It’s a short string” is printed.
That is great.
You can use this in the conditional statement of the for loop, as well.
If you want to iterate from each of the characters in a string and convert every letter into a lower-case letter, but you are not yet aware of how many characters the string has, then you can simply give the str.length property as a conditional statement.
for (let i = 0; i < str.length; i++) {
console.log(str[i].toUpperCase());}
As you can see in the output console, every character is shown in the console separately and converted into uppercase letters, as well.
So, this is how you can apply it to a lot of different scenarios according to your needs.
Interesting Fact
Here is an interesting fact for you guys.
Let us now try to dodge the string length property by assigning it a numeric value.
You will see that it will either print the assigned value or the real length of the string.
So, first, assign it a value
str.length = 10;
And now, we will try to console the length of the string.
console.log(str.length);
And, as you can see, it does not show the assigned value.
It shows that the length of the string or the number of characters in the string are being calculated at run time, and then it displays the output.
Conclusion
In this article, you learned what the string length property is and you have seen its applications in a few different examples.
I hope this article proved helpful in understanding the string length property and its implementations.
You can read on to learn more about Javascript at linuxhint.com.
Javascript toLowerCase Function
Javascript is a popular scripting or programming language.
Programmers often use Javascript to manipulate or manage data.
For example, say, you are getting some data from a user in the fields of an HTML form.
While getting the data from the user, you cannot control what the user is typing.
But, you also need to show the data in a good format.
Users may input capital letters where they are not needed or vice versa.
While saving data to the database or showing data to a web page, as a programmer, it is necessary to take care of this function.
For this purpose, we have Javascript’s built-in function toLowerCase() for converting a string to lower-case letters.
Syntax
The syntax for Javascript’s toLowercase() function is as follows:
string.toLowerCase();
The toLowerCase() function converts all the alphabets in a string into lower-case letters.
This function does not change the original value of the variable.
Instead, the function creates a new string for the instance.
In this way, the function does not take any arguments, although the parentheses “()” are used for taking arguments.
But, with the toLowercase() function, you follow the same conventions of a function.
Let us now look at some examples.
Examples
Suppose there is a string that includes some uppercase and lowercase letters, such as the following string:
let str = "Welcome to thE LinuxHint."
But, we need to convert the string entirely into lower-case letters.
So, we will simply apply the following:
str.toLowerCase();
As you can see, the string has been converted to a formatted string.
All the letters are now in lower-case format.
It is as simple as that.
This function is for the string.
But, this is not only restricted/limited here.
We can apply the function to an array of strings and even to an array of objects containing strings, as well.
Let us take a look:
First, we will write down the array of strings, as follows:
let arr = ["Hi", "LinuxHint", "GREAT"]
Now, to change the term “GREAT” to all lowercase letters, we will apply the following:
arr[2].toLowerCase();
where ‘2’ is the index of “GREAT”.
As you can see, now, the term “GREAT” has been converted into lower-case letters.
We did something similar for two other strings: [0] for the term “Hi” and [1] for the term “LinuxHint.”
Let us now see how we can apply this function to an array of objects in which the objects contain the string, as follows:
let arr = [{"name":"John"},{"name":"BOB"},{"name":"Ivan"}]
To convert the term “BOB” to all lower-case letters, we will change it as follows:
arr[1].name.toLowerCase();
Awesome.
As you can see, we can do a lot with Javascript’s toLowerCase() function.
Conclusion
In this article, we showed you how to convert string characters to lower-case.
We also showed you how to apply the same function to an array of strings and an array of objects containing strings.
I hope that this article proved beneficial for converting an informal string into a cleaner and more formal-looking lowercase string.
You can learn more about Javascript at linuxhint.com.
Javascript split
Javascript is a scripting or programming language of the web.
Strings are an important part of the variables in any programming language.
We often need to manipulate string according to our needs.
In this article, we will talk about the javascript’s split string method which is used to split the string according to our needs.
So, let’s take a look at what is a string and what does split string method do.
The string is just a simple text or characters which can include the alphabets, numbers, or symbols.
Javascript’s split() method is called upon when it is required to split the string into the array of substrings in accordance to the separator that you provide.
Syntax
Let’s have a look at the syntax of the split method.
string.split([seperator][, limit]);
Here, the separator could be a single character using which you would like to split the string.
And the limit is the limit of splits.
When the number of substrings becomes equal to the limit, the split() method stops.
Let’s dive in and get a couple of examples done for the understanding of the split() function.
Examples
We suppose a string “Linuxhint is great and working hard to grow.”.
Now, let’s try to split the string into arrays of string using the split() method.
By providing the “ ” space character as a separator.
But, without providing the limit.
Later, we will do it with the limit.
linux.split(" ");
As you can see that the split() method has returned the array of substrings, based on the “ ” space.
Now, let’s see what happened if we provide a limit as well.
linux.split(" ", 3)
As you can see that the split() function stopped splitting the string, and it would stop splitting the string when the count is equivalent to the number of substrings.
Now, let’s see if we don’t provide a separator just an empty string, and calls the split() function.
linux.split("");
As you can see that the function has split and returned the array of each character separated.
Now, let’s see if we don’t provide both of the arguments and just calls the split() function.
linux.split();
Great, the split() function has returned an array with a single substring in it that is the whole string
Pro tip
What if we want to split the string on the base of two separators or we want separators as well in the output array of substring? Luckily, there is a solution as well, We can provide regular expressions as a separator as well.
So, let’s see how can we split the string with two separators.
Space “ “ character and “i” character
linux.split(/\ |i/);
Alright! It worked great.
As we expect it to split.
Now, what if we want to include the separators as well in the array of the substring.
We will simply add parenthesis() around the regular expression.
linux.split(/(\ |i)/);
Perfect, as you can see that the separators are also included in the array of substrings.
Conclusion
In this article, we have seen that how can we split a string on the base of a separator provided and how can we apply the limit to the split() function.
We came across how we could provide regular expressions in compliance with our needs and requirements.
So, have a happy and the best learning of javascript with linuxhint.com.
Javascript replace
Javascript is a scripting or programming language of the web.
Strings are an important part of the variables in any programming language.
We often need to manipulate or extract some specific string according to our needs.
You must have seen it often at a lot of websites that on a click of a button or something the text got changed.
How can we find and replace some specific words in a long paragraph? Do we have to change all the code? Of course not, we have a replace() method to replace the substring with a new provided string.
So, let’s take a look at what is a string and how can we replace a substring with another string.
The string is a simple text or characters which can include the alphabets, numbers, or symbols.
Javascript’s replace() method finds the provided substring and change/replace that substring with a new provided string.
Syntax
Syntax for the replace() method is
string.replace(substring, newstring);
substring can be any value from the string to which we want to replace
newstring is the value that replaces the substring(first parameter).
Examples
Now, if we take a look at some examples.
We suppose a string “Linuxhint is great and linuxhint is working great.”.
In this string, I have repeated the same word “great” and “linuxhint” intentionally.
The purpose of this will be right in front of you in a moment.
Now, let’s try to replace the word “great” with let’s say “awesome” using the replace() method.
linux.replace("great", "awesome");
Here you can see the problem that the first occurrence of “great” gets replaced.
But, the second one doesn’t.
So, here comes the concept of the regular expression.
We can also give the regular expression instead of the substring to the replace() method.
So let’s modify the syntax a little bit that we can give regular expression as well.
string.replace(substring|regex, newstring);
regex is a regular expression object.
The matches will be replaced by the newstring.
If we want to replace every single occurrence of the word “great” then we shall pass the regular expression with a ‘g’ flag, which is a short form for global.
Take a look below to get an idea about what exactly I mean.
linux.replace(/great/g, "awesome");
Perfect, all the occurrences of “great” are changed.
But, now we may face a problem if we try to change all the occurrences of “linuxhint” to let’s say “our website” using the same technique.
Let’s try to do that first, then we will see how can we resolve that.
linux.replace(/linuxhint/g, "our website");
As you can see that.
Although we have provided the global flag with the regular expression.
But, the first occurrence doesn’t get changed.
This is because of case-sensitivity.
So, we need to provide a case-insensitivity flag ‘i’.
We can do that by simply adding the ‘i’ flag along with the ‘g’ flag.
Like,
linux.replace(/linuxhint/gi, "our website");
Great.
As you can see that all the occurrences of “linuxhint” are changed regardless of the case-sensitivity.
Pro tip
We have two protips for you.
One is that we can give multiple substrings in a regular expression as well using the OR “|” operator.
The second one is that we can also provide a function instead of the newstring.
So, the final syntax that you should take with you is
string.replace(substring|regex, newstring|function);
Let’s have a look at an example.
To understand how it works.
In this example, we will change/replace both “great” & “linuxhint” using a single replace method and later we will provide some tasks to do in a function, in which we will change the matches to the uppercase.
linux.replace(/great|linuxhint/gi, (m)=>{return m.toUpperCase()});
Alright! As you can see that both of the words “great” & “linuxhint” are converted into the uppercase letters, successfully.
Conclusion
In this article, we have learned that how can we use the replace() method to replace the substring and how can we use the regular expression to give multiple values along with the global and case insensitive flag.
I hope this article has helped you to thoroughly understand the replace() method.
So, keep on learning javascript with linuxhint.com.
Javascript String to Int
Javascript is a language of the web and managing data is an important aspect of any programming language.
We often need to manipulate or manage variables according to our needs.
Sometimes we need to perform arithmetic operations so, we can’t do that with strings.
We need integers to do that.
Since Javascript is a language of the web now.
Speed optimization has become very important in this era.
We have to think and manage every single byte if we can.
We must know and care about memory because the strings take more memory than integers.
We need to keep things very simple.
But, what if we have to perform some arithmetic operations.
If, variables are in string type.
Do we have to reinitialize the variable with integer type? Of course not! It will even take more memory.
But, what if we have a function that will convert or parse the string into the integer and we can perform our tasks.
So, in this article, we are gonna see that how can we convert or parse a string into the integer using the parseInt() function.
The parseInt() is a function to which we can pass a string as an argument and it will return us an integer if it exists.
This function returns NaN(Not a Number).
If, no number found in that string.
This function also returns NaN if there exists any character before the number.
Syntax
Let’s take a look at the syntax of the parseInt() function.
parseInt(value [, base]);
Here,
Value is the string that we want to parse into the integer.
And the base is the base number of the provided string to which we want to convert into a decimal number.
It is an optional value.
Let’s have look at a couple of examples to understand more clearly.
Examples
parseInt("34"); // 34</td>
Now, let’s try to give a float number.
parseInt("34.53"); // 34
As you can see.
It only prints the 34.
Let’s try to put a space before or after the number.
parseInt(" 34 "); // 34
It worked fine.
But, if we put any character before the number.
parseInt("the 34"); // NaN
It prints NaN(Not a Number).
The same applies to the empty string.
Pro tip
Now, what if we try to give the base number along with the value.
Like, the base of the binary number system is 2.
parseInt("34", 2); // NaN
Ok, since 3 and 4 are not the numbers of a binary number system.
It prints NaN.
Now if we provide it a true binary number.
It should print the decimal number against that binary number.
parseInt("10011011", 2); // 155
Here comes an interesting thing about this function.
Like, if we keep on providing the binary number 0’s and 1’s.
It will keep on converting that number into the decimal number system.
But, when we start to give a non-binary number system.
It will stop right there and won’t convert any further.
But, until we keep on giving the binary numbers.
It keeps on converting.
parseInt("100110113432", 2); //155
Alright! We can also do the same tasks with the Octal number system and Hexadecimal number system using the parseInt() function.
Conclusion
In this article, we have learned that how can we use the parseInt() function to convert the string into an integer.
We have also learned about some exceptional cases of the parseInt() function and how does it help in converting the number systems as well.
I hope this article was beneficial and helpful for understanding the conversion of strings into integers.
So, keep on learning javascript with linuxhint.com.
Javascript Substring
Javascript is a scripting or programming language of the web.
Strings are an important part of the variables in any programming language.
We often need to manipulate or extract some specific string according to our needs or somewhere we don’t have to show all the text.
You must have seen some data (if we specifically talk about strings) on the web that are not fully shown on the screen.
How did that happen? How can we get some specific part of a string? So, let’s take a look at what is a string and how we can take a substring of that string.
String & substring
A string is simply a text or characters which can include alphabets, numbers, or symbols.
A substring, as it’s in its name.
A subpart of a String.
If we talk about string.
Javascript has some built-in functions for manipulating string.
One of them is substring() a function that serves our purpose.
If we want to extract some specific parts from a string.
We can use substring() function.
Syntax:
The syntax for the substring() function is
string.substring(startIndex, endIndex);
startIndex is the index from where you want to start the string.
endIndex is the index where you want to end the string.
Examples:
If we suppose a string, like “linuxhint”.
We want to just get the “Linux” from the “linuxhint”.
So, we will do that using substring() function like this
name.substring(0, 5); // “linux”
Now, if you notice that it doesn’t include the 5th index element.
But, it picked the 0th index element.
Which implies that startIndex gets included.
While endIndex doesn’t get included.
So, now if we want to pick the “hint” from “linuxhint”.
Although there are only “0” to “8” indexes.
But, we will give “9” as a value to the endIndex.
name.substring(5, 9); // “hint”
We can give it only one value as well.
name.substring(5); // “hint”
It will start from that index and continues until the end of the string.
Alright! Now, we have seen the syntax and how does it work.
Let’s see some of its exceptional cases.
Exceptional Cases
Let’s try to give a startIndex greater than the endIndex and some negative values to see how does it respond.
startIndex > endIndex
If we give it a startIndex greater than the endIndex.
name.substring(5, 2); // “nux”
It has swapped both values and printed the string from the 2nd index to the 5th index.
So, if we write either name.substring(5, 2) or name.substring(2, 5).
//both will print the same output
name.substring(5, 2); // “nux”
name.substring(2, 5); // “nux”</td>
It will print out the same output.
Negative values
substring() function doesn’t take negative values.
If we give it a negative value.
Since there is no negative index.
It takes it as a “0”.
Either we give a negative value to the startIndex or the endIndex.
This function considers it a “0”.
name.substring(-5, 2); // “li”
If we give a negative value to the endIndex.
The function will swap the values.
Because negative value will be converted to “0” and “0” will be the lowest value.
name.substring(5, -2); // “linux”
And, if we give a negative value to both of the indexes.
The function will print an “” empty string.
name.substring(-5, -2); // “”
Pro tip
By the way, here is a pro tip.
We can use string.length function within a substring() function.
name.substring(5, name.length); // “hint”
Or we can give it a string.length – [value], like
name.substring(5, name.length - 1); // “hin”
Conclusion
So, after reading this article, you should have a profound knowledge of the substring() function.
Because you have learned all about the substring() function.
All of its exceptional cases and how can we manipulate the string according to our needs.
So, have fun with the strings.
Connecting MySQL with NodeJS
MySQL server is a very popular database server and it is supported by mostly used programming languages, such as PHP, Python, Perl, Java, C#, etc.
It is an open-source application, so anyone can download this application for storing, retrieving, updating and deleting data by using database queries.
You will require the server and client packages to be installed in your system to perform different types of database operations in the database server.
MySQL server is now becoming popular for Node developers also.
Node developers start using MySQL server with MongoDB for some special features of the MySQL server.
How you can make a connection with MySQL server using the node-mysql client is shown in this tutorial.
Prerequisite:
Before starting this tutorial you have to confirm that MySQL server and client packages are installed and working properly in your system.
If you install the MySQL server for the first time then the password of root user is empty by default.
But you have to set the password for the root user to make a connection with MySQL server using the node-mysql client.
You can check this tutorial to know how to change the root password of the MySQL server.
Run the following commands to work as a root user and connect with MySQL server by using MySQL client.
$ sudo -i
$ mysql -u root -p
Enter the root password and run the following SQL commands to create a new database, create a table on that database and insert some records in that table.
The following command will create a database named mydb.
CREATE DATABASE mydb;
The following command to select the database for doing database operations.
use mydb;
The following command will create a table named book in the database mydb.
CREATE TABLE book (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(50) NOT NULL,
author VARCHAR(50) NOT NULL,
price int(5));
The following command will insert four records into book table.
INSERT INTO book values
(NULL,'Learning PHP and MySQL', 'Robin Nixon', 45),
(NULL,'Learning JQuery', 'Jonathan', 35),
(NULL,'Angular in Action', 'Jeremy', 50),
(NULL,'Mastering Laravel', 'Christopher', 55);
Install mysql client for nodejs:
Run the following command to check nodejs is installed in the system before running the command of installing mysql client of nodejs.
It will show the installed version of nodejs.
$ node -v
If it not installed then you have to install it by running the following command.
$ sudo apt-get install nodejs
You will require another package named npm to be installed in the system to install mysql client for nodejs.
If it is not installed before run the following command to install npm.
$ sudo apt-get install npm
Now, run the following command to update the system.
$ sudo apt-get update
The following command will install mysql module for nodejs that will work as mysql client.
$ npm install mysql
Simple MySQL connection using NodeJS:
Create a JS file named connection1.js with the following script to make a connection with the previously created database named mydb and read data from book table.
mysql module is imported and used for creating a simple connection with the MySQL server.
Next, a query will be executed to read all records from book table, if the database is connected properly.
If the query executed properly then all records of book table will be printed in the terminal and the database connection will be closed.
connection1.js
// Import mysql module
let mysql = require('mysql');// Setup database connection parameter
let connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '1234',
database: 'mydb'});// Connect with the database
connection.connect(function(e) {if (e) {// Show error messaage on failurereturn console.error('error: ' + e.message);}// Show success message if connected
console.log('\nConnected to the MySQL server...\n');});// Set the query message
$query = 'SELECT * from book';// Execute the database query
connection.query($query, function(e, rows) {if(e){// Show the error message
console.log("Error ocurred in executing the query.");return;}/* Display the formatted data retrieved from 'book' table
using for loop */
console.log("The records of book table:\n");
console.log("Title\t\t\t\t Author\t\tprice\n");for(let row of rows) {
console.log(row['title'],"\t\t",row['author'],"\t","$",row['price']);}});// Close the database connection
connection.end(function(){
console.log('\nConnection closed.\n');});
Output:
Run the following command to execute the script.
$ node connection1.js
The following output will appear after running the script.
Pooled MySQL connection using NodeJS:
Making a simple MySQL connection with NodeJS using mysql module is shown in the previous example.
But many users can connect with the database server at a time through the application when the application is created with MySQL database for production purposes.
You will require the express module to handle concurrent database users and support multiple database connections.
Run the following command to install the express module.
$ npm install express
Create a JS file named connection2.js with the following script.
If you connect with MySQL with the following script then 10 concurrent users will be able to make a connection with the database server and retrieve data from the table based on the query.
It will make a connection at the port 5000.
connection2.js
// Import mysql modulevar mysql = require('mysql');// Import express modulevar express = require("express");// Define object of express modulevar app = express();// Make database connection to handle 10 concurrent usersvar pool = mysql.createPool({
connectionLimit :10,
host : 'localhost',
user : 'root',
password : '1234',
database : 'mydb',
debug : true});/* Make pooled connection with a database and read specific records from a table of that
database */function handle_database(request,response) {// Make connection
pool.getConnection(function(e,connection){if (e) {
//Send error message for unsuccessful connection and terminate
response.json({"code" : 300, "status" : "Database connection errror"});
return;}// Display success message in the terminal
console.log('Database connected');// Read particular records from book table
connection.query("SELECT * from book where title like '%PHP%' or title like
'%Laravel%'",function(e,rows){ connection.release();if(!e) {
// Return the resultset of the query if it is successfully executed
response.json(rows);}});// Check the connection error occurs or not
connection.on('error', function(e) {
response.json({"code" : 300, "status" : "Database connection errror"});return;});});}// Call the function for making connections
app.get("/",function(request,response){-
handle_database(request,response);});// Listen the connection request on port 5000
app.listen(5000);
Output:
Run the script from the terminal like the previous example.
It will wait for the connection request after running the script.
$ node connection2.js
Now, open any browser and go to the following URL to send a connection request.
http://localhost:5000
The following output will appear as a response after executing the query.
If you open the terminal now then you will see the following output.
Ten connection requests can be sent at a time from 10 browsers in the way mentioned above.
Conclusion:
The most simple ways to work with MySQL and NodeJS are shown by two examples in this tutorial.
If you are a new Node developer and want to work with MySQL database then I hope you will be able to do your task after reading this tutorial.
Simple NodeJS Application
In the last couple of years, the world has undergone some fascinating technological changes.
Each day, something new is developed that offers an improvement over its predecessor and gives us access to a whole new dimension.
One certain region that has seen a significant improvement in its features and popularity is the web development sector, particularly NodeJS, which has become many developers’ first choice for back-end development.
What actually is NodeJS?
NodeJS is an open-source JavaScript platform used for developing and executing back-end services called APIs (Advanced Programming Interfaces).
These are the services that power up the client applications such as web apps that run on the browser and mobile applications.
NodeJS is important because these client applications are just a surface for users to see and interact with.
In addition to this, they need to talk to some service on the server or in the cloud for the storage of data, sending emails or pushing notifications.
This is where NodeJS comes into the picture which allows users to create server-based applications and produce real time back-end services that can be used to power up client applications.
Being highly scalable and superfast, NodeJS is a great choice for development and hence today we’ll be looking at how to make a simple NodeJS application.
Step 1: Installing NodeJS
Before moving on the development phase, let us first see how to install NodeJS on our Linux based desktops.
There are actually multiple ways to install NodeJS on a Linux based computer.
We, however, will only be looking at two methods of installing NodeJS.
Step 1(a): Installing NodeJS using NVM
In this method, we will be using the Node Version Manager (NVM) to install NodeJS.
A huge benefit of using this is that there are no permission issues for using NodeJS.
First of all, we have to install nvm which can be done by the following command:
$ wget -qO- https://raw.githubusercontent.com/nvm-sh/nvm/v0.35.1/install.sh | bash
This command adds nvm to your path profile and extracts all the nvm data in the directory ~/.
nvm
To check whether nvm has been installed correctly, restart the terminal and run:
$ command -v nvm
If you see nvm as the output, then it has been successfully installed.
Now we’ll be installing NodeJS and npm which is basically an ecosystem of NodeJS libraries.
To do this, simply run the following command that will install the most recent version of NodeJS:
$ nvm install node
You can also install any specific version of NodeJS that you want to install.
For this tutorial, we’ll be installing the version 12 of NodeJS.
$ nvm install v12.16.1
Once installed, you can check your NodeJS and npm installed versions by running the following commands:
$ node -v
$ npm -v
Step 1(b): Installing NodeJS using Ubuntu official repository
One huge advantage of installing NodeJS in this way is that Ubuntu has a stable version of NodeJS in its official repository.
First of all, the following command will be run to update our system’s apt cache and packages to the latest versions so that no issues arise during installation:
$ sudo apt-get update
Next, we will be installing NodeJS with the following command:
$ sudo apt install nodejs
Once installed, you can check your NodeJS installed version by running the following command:
$ node -v
In this method, we also have to install npm, the ecosystem of NodeJS libraries.
This can be done by inputting the following command into the terminal:
$ sudo apt install npm
Similarly, you can check your npm installed version by running the following command:
$ npm -v
Step 2: Coding a NodeJS Application
For this tutorial, we’ll be creating a simple HTTP Server which will listen to the client on port number 8080 and output Hello World as a response to the client.
The following is the complete code:
let http = require('http')
server = http.createServer(function(request, response) {
response.write('Hello World')
response.end()})
server.listen(8080)
console.log ("Server Running")
Let us now look at each line of code to understand what is actually happening here.
Code Explanation:
In Node JS, there are some built in modules available.
These are functions that have already been defined in NodeJS and provide certain functionality in our applications.
These modules can be imported using the require keyword.
let http = require('http')
In the first line of our code, we are importing the HTTP built in module of NodeJS.
The HTTP module is used here so that we can create a server in our application that can listen for HTTP requests on a given port.
server = http.createServer(function(request, response)
Over here, we use a method of the HTTP module called createServer which, as the name says, creates a server instance.
In this, we pass a function through here which takes up two parameters – a request object and a response object.
Now whenever a request is made to our server, this function will be called.
The response object comes loaded with details about the request that has been made and the response object is something that we can use to send a response back to the client.
response.write('Hello World')
response.end()
Over here, response.write is used to write a response to the client.
This is how things can be printed on the browser.
In this case, this will allow us to print Hello World on the browser.
The response.end() lets the browser know that the request has ended and sends the response to the browser.
server.listen(8080)
console.log ("Server Running")
The server.listen function is used here by our server to listen to the client on port number 8080.
It is important to note that any port that is available can be used here.
The last line console.log is used to print anything on the terminal.
In this case, we are printing Server Running so that we know the server has started.
Step 3: Running and Testing our NodeJS Application
Now that we have our code written and understand what is happening in it, let us now run it and test whether it is working or not.
To do this, open the directory, where you have saved your file containing the above NodeJS code and along with this, also open the terminal.
In order to run a NodeJS file, simply type in the following command in the terminal:
$ node filename.js
filename here refers to the name of your file.
In my case, I’ve stored my code in a file called sample.js.
See below:
$ node sample.js
Now our server seems to be running.
Let us now check to see if our response has been sent to the client.
To do this, open your browser and enter localhost: port.
In my case, I’ll be running the command: localhost:8080.
See the image below for better understanding:
We can clearly see our output Hello World displayed on the page.
Voila, we were successful in creating a simple NodeJS Server.
Why use NodeJS over its Alternatives?
In today’s world, JavaScript has completely changed the face of web development.
This has thus led to NodeJS becoming a popular choice for back-end development.
Along with using JavaScript as its core, NodeJS is highly fast, extremely flexible and great for prototyping and agile development.
Moreover, using NPM (Node Package Manager) as its ecosystem which is the largest ecosystem available for open-source libraries, it grants multiple tools and modules to developers which further increases its demand.
All these reasons make it a great choice for web development.
How to install the latest Node.js on Linux?
Node.js is a runtime JavaScript environment that is used on the server-side.
Node.js is a full-stack software building solution but is mostly used at the back end to build the applications.
Node.js uses the NPM package manager as a default package manager, which is known as the most used software registry.
There are several methods to install Node.js on Ubuntu 20.04 LTS, but here, we will learn the two most efficient and easiest methods to install it.
Using APT package repository
Using the APT package repository through NodeSource PPA
Let’s get started with the easiest one.
Install Node.js on Ubuntu 20.04 using APT
Installing any software through the APT package repository is the easiest way to install the software on Ubuntu.
First, update the system’s package repository.
$ sudo apt update
Then, install the Node.js using the simple apt install command with the sudo privileges.
$ sudo apt install nodejs -y
In this command, the “-y” flag is added to automatically answer “yes” if any prompt occurs.
After installing the Nodejs, if you want to install NPM as well, run the command.
$ sudo apt install npm -y
After a while, NPM will be installed as well.
The above two commands will install all the other tools required for compilation.
To verify and check the versions of the Node.js and NPM, execute the following two commands.
$ nodejs --version
$ npm --version
As you can see, version 10.19.0 of Node.js and version 6.14.4 of NPM is installed.
Install Node.js on Ubuntu 20.04 through NodeSource PPA
In case you want to install some specific or older version of Node.js, it is better recommended that you use the official Private Package Archive(PPA) managed by the NodeSource.
At the date of writing this post, NodeSource has the following Node.js versions available:
Node.js v15.x
Node.js v14.x
Node.js v12.x
Node.js v10.x
Furthermore, you can check the version provided by the NodeSource by visiting their Github page (GitHub – nodesource/distributions: NodeSource Node.js Binary Distributions).
For example, to install the Node.js v15.x, you first need to have the curl installed on your system.
To install curl, perform the following.
$ sudo apt install curl -y
After installing the curl, execute the following command to run Nodesource’s installation script using the curl command.
$ curl -sL https://deb.nodesource.com/setup_15.x | sudo -E bash -
Once the NodeSource’s PPA is configured for Node.js on your system, now install the Node.js by typing the following command.
$ sudo apt install nodejs -y
Let’s verify the versions of Node.js and NPM by typing the commands.
$ node --version
$ npm --version
You can witness that the required versions are installed successfully.
Wrap up
These are the two different methods to install Node.js on Ubuntu 20.04 LTS.
You can either install it via the APT package repository, which is the easiest way, or go with your desired version with the official PPA introduced by NodeSource.
Installing Node.js on CentOS 8
In this article, I am going to show you how to install Node.js on CentOS 8.
So, let’s get started.
Installing Node.js using Package Manager:
Node.js is available in the official package repository of CentOS 8.
So, you can easily install it on CentOS 8 using DNF or YUM package manager.
First, update the CentOS 8 package repository cache with the following command:
$ sudo dnf makecache
The CentOS 8 package repository cache should be updated.
Now, to install Node.js and NPM package manager on CentOS 8 from the official package repository of CentOS 8, run the following command:
$ sudo dnf install nodejs npm
Now, to confirm the installation, press Y and then press <Enter>.
Node.js and NPM should be installed.
Once Node.js and NPM is installed, check whether Node.js is working correctly as follows:
$ node --version
As you can see, Node.js v10.16.3 is installed.
Also, check whether NPM is working correctly as follows:
$ npm --version
As you can see, NPM v6.9.0 is installed.
The same way, check whether NPX is working as follows:
$ npx --version
As you can see, NPX v6.9.0 is installed.
Installing Node.js Manually from the Official Website of Node.js:
The version of Node.js and NPM in the official package repository of CentOS 8 is old.
At the time of this writing, the latest LTS version of Node.js is v12.13.0 and the latest version of Node.js is v13.0.1.
If you want to install the latest LTS version of Node.js or the latest version of Node.js on CentOS 8, you will have to download Node.js from the official website of Node.js and manually install it on CentOS 8.
First, visit the official website of Node.js.
Once the page loads, click on the LTS version button if you want to install the latest LTS version of Node.js.
Otherwise, click on the Current version button if you want to try out the latest version of Node.js.
Your browser should prompt you to save the file.
Select, Save File and click on OK.
Your browser should start downloading the Node.js archive.
It may take a while to complete.
If you’re using a headless version of CentOS 8, then visit the official website of Node.js from any browser.
Once the page loads, right click (right mouse click) on the download button and copy the download link.
Now, SSH into your CentOS 8 machine and use wget to download the Node.js archive file using the link that you’ve copied earlier as follows:
$ wget https://nodejs.org/dist/v12.13.0/node-v12.13.0-linux-x64.tar.xz
Once Node.js archive file is downloaded, navigate to the directory where the archive file is downloaded (usually ~/Downloads) as follows:
$ cd ~/Downloads
The Node.js archive file should be there.
$ ls -lh
Now, you have to extract the Node.js archive file.
I will extract it in the /opt directory.
If you want, you can extract it to some other directory.
Just replace /opt with the directory path where you want to extract the Node.js archive file.
To extract the Node.js archive file in the /opt directory, run the following command:
$ sudo tar xvJf node-v12.13.0-linux-x64.tar.xz -C /opt
Node.js archive file should be extracted in the /opt directory.
Once the Node.js archive file is extracted, a new directory (node-v12.13.0-linux-x64 in my case) should be created in the directory where you extracted it.
$ ls /opt
Now, you have to add the path of Node.js to the PATH environment variable in order to access Node.js, NPM and NPX binaries easily.
You can create a shell script in the /etc/profile.d/ directory which will automatically update the PATH environment variable every time your CentOS 8 machine boots.
To create a new shell script /etc/profile.d/node-v12.sh, run the following command:
$ sudo vi /etc/profile.d/node-v12.sh
Now, press I to switch to the Vi INSERT mode and type in the following lines of codes in the node-v12.sh file.
export NODE_VERSION=v12.13.0export NODE_DISTRO=linux-x64export NODE_HOME="/opt/node-${NODE_VERSION}-${NODE_DISTRO}"export PATH="$PATH:${NODE_HOME}/bin"
NOTE: By the time you read this article, new versions of Node.js may be released.
So, make sure to change NODE_VERSION from v12.13.0 to the version of Node.js you’re trying to install.
If you’re extracting the Node.js archive file to some other directory than /opt, then change /opt to the directory you’re extracting the Node.js archive file.
The final shell script file should look as follows.
To save the file node-v12.sh, press <Esc> to switch to Vi COMMAND mode, type in :wq! and then press <Enter>.
Now, reboot your CentOS 8 machine with the following command:
$ sudo reboot
Once your CentOS 8 machine boots, verify whether the shell script set all the Node.js environment variables correctly with the following command:
$ env | grep NODE
As you can see, the Node.js environment variables are correctly set.
Now, check whether the PATH environment variable is updated correctly with the following command:
$ echo $PATH
As you can see, the Node.js binary path is in the PATH environment variable.
Great!
Now, check whether Node.js is working correctly with the following command:
$ node --version
As you can see, the version of Node.js installed is v12.13.0.
So, it’s working
Also, check whether NPM is working correctly with the following command:
$ npm --version
As you can see, the version of NPM installed is 6.12.0.
It’s working as well.
Lastly, check whether NPX is working correctly with the following command:
$ npx --version
As you can see, the version of NPX installed is 6.12.0.
It’s also working.
So, that’s how you install Node.js on CentOS 8.
Thanks for reading this article.
Installing Node.js using Package Manager:
Installing Node.js on Debian 10
Node.js is a server side JavaScript runtime.
Node.js is open source and cross platform.
Node.js runs on Linux, Windows and macOS.
It is mainly used to develop software APIs and networking applications.
In this article, I am going to show you how to install Node.js on Debian 10 and how to run a simple Node.js program on Debian 10.
So, let’s get started.
Installing Node.js 10 LTS:
Node.js 10.x is the latest LTS version of Node.js at the time of this writing.
Luckily, it is available in the official package repository of Debian 10.
So, you can easily install it using the APT package manager on your Debian 10 machine.
First, update the APT package repository cache with the following command:
$ sudo apt update
The APT package repository cache should be updated.
Now, install Node.js from the official Debian 10 package repository with the following command:
$ sudo apt install nodejs
Now, to confirm the installation, press Y and then press <Enter>.
The APT package manager will download and install all the required packages.
Node.js 10.x should be installed.
As you can see, the Node.js version installed from the official package repository is v10.15.2.
$ node --version
Node.js has its own package repository to help you out in your work.
Luckily, Debian 10 packages a lot of common and stable Node.js packages.
You can easily download them from the official package repository of Debian 10.
The Node.js Debian 10 package names start with node-*
For example, I searched for express.js Node.js package on the official Debian 10 package repository.
As you can see, the package exists.
The express-generator package exists as well.
The package names are node-express and node-express-generator in Debian 10.
You can easily use the APT package manager to install these packages and use them in Node.js 10.
I also searched for the Node.js package bluebird.
It exists as well.
If you rather want to install Node.js packages using NPM, then you have to install NPM from the official package repository of Debian 10 with the following command:
$ sudo apt install npm
Now, confirm the installation by press Y followed by <Enter>.
The APT package manager will download and install all the required packages.
At this point, NPM should be installed.
As you can see, the NPM version installed from the Debian 10 package repository is 5.8.0.
The Node.js packages that are in the Debian 10 package repository are very stable and well tested.
You can use them if you want.
Installing Node.js 12:
At the time of this writing, the latest version of Node.js is version 12.x.
But, it is not available in the official package repository of Debian 10.
You have to install it manually from the official package repository of Node.js.
Before you install Node.js 12.x, you have to install some dependency packages from the Debian 10 package repository.
First, update the APT package repository cache with the following command:
$ sudo apt update
The APT package repository should be updated.
Now, install the dependency packages build-essential and curl with the following command:
$ sudo apt install build-essential curl
Now, press Y and then press <Enter> to confirm the installation.
The dependency packages should be installed.
Now, add the official Node.js 12.x package repository with the following command:
$ curl -sL https://deb.nodesource.com/setup_12.x</a> | sudo bash -
The Node.js 12.x package repository should be added and the APT package repository cache should be updated.
Now, install Node.js 12.x with the following command:
$ sudo apt install nodejs
The APT package manager should download and install all the required packages.
Node.js 12.x should be installed.
As you can see, I am running Node.js 12.7.0.
$ node --version
Node.js installed from the official Node.js package repository installs NPM by default.
As you can see, I am running NPM 6.10.0.
Writing Your First Node.js Program:
In this section, I am going to show you how to write your first Node.js program.
First, create a project directory (let’s call it ~/hello-node) as follows:
$ mkdir ~/hello-node
Now, navigate to the project directory ~/hello-node as follows:
$ cd ~/hello-node
Now, create a new file welcome.js in the project directory ~/hello-node and type in the following lines of code in the welcome.js file.
let http = require('http');
const PORT = 8080;
let server = http.createServer((req, res, next) => {
res.writeHead(200, {'Content-Type': 'text/html'});
res.end('<h1>Welcome to LinuxHint!</h1>');});
server.listen(PORT, () => {
console.log("Visit http://localhost:" + PORT + " from your web browser.");});
The final welcome.js program looks as follows:
Now, to run the Node.js program welcome.js, run the following command:
$ node welcome.js
As you can see, the welcome.js program is running.
Now, visit http://localhost:8080 from your web browser and you should see a welcome message as shown in the screenshot below.
So, that’s how you install Node.js on Debian 10 and run your first Node.js program.
Thanks for reading this article.
Recognizing a face using JavaScript
What are the options? Many solutions exist for Machine Learning.
When you look around for ways to identify faces, you come up with a host of solutions.
Many are generic, some are interfaces to existing frameworks.
For JavaScript, you have a few popular ones to choose from.
You may even be confused by the array of solutions.
Even for face recognition you have several options.
Many, most actually, are for Python but you can also find a few.
Frameworks that are aimed specifically at face recognition are face,js and face-recognition.js.
The latter is considered obsolete though.
The smallest, in terms of code, is pico.js With about 200 lines of code it can detect your own face using your webcam.
The Pico code comes with a trained set already, which means that it will not improve while you are using it.
For the curious, the pre-trained classification cascades are available on their GitHub repository.
If you do want to train it yourself, there is a learn function you can use.
This is a C program available on GitHub.
This is a long process to complete making it an interesting exercise rather than something useful.
One of the more interesting API’s is face-api.js, this one uses TensorFlow.js for the machine learning part.
How does it work?
The simplest example of machine Learning is a pair of parameters such as the petals of the iris flower.
This is the most common initial data set when you want to start learning Machine Learning.
The data can be summarised in simple tables.
Sepal length |
Sepal width |
Petal length |
Petal width |
Class |
5.1 |
3.5 |
1.4 |
0.2 |
Iris Setosa |
4.9 |
3.0 |
1.4 |
0.2 |
Iris Setosa |
7.0 |
3.2 |
4.7 |
1.4 |
Iris Versicolor |
6.4 |
3.2 |
4.5 |
1.5 |
Iris-versicolor |
6.9 |
3.1 |
4.9 |
1.5 |
Iris-versicolor |
6.3 |
3.3 |
6.0 |
2.5 |
Iris-virginica |
5.8 |
2.7 |
5.1 |
1.9 |
Iris-virginica |
|
|
|
|
|
As you can see from the table, it is now possible to find the sizes which best match a certain flower.
This is not an absolute truth but it can get very accurate with enough data points.
The question now becomes: How do you represent an image as a long list of values? Or a face for that matter? Well, the short story is that you convert the picture to the value of the intensity of each pixel.
Starting from there, you can decide where lines and or points go that depict a face.
What a face actually is has been determined by a pre-trained model.
If you apply that to a number of pictures of the person you are trying to detect, then a table similar to the Iris one above can be used for determining which face it is.
How it actually works is a bit more complex than that.
For you to create your own solution, you need to use a library made for it.
Fortunately, there are many free and open source solutions available.
What are the options?
There are many libraries for using JavaScript, one is face-api.js.
The others may more capable choices but this one has a very simple demo page.
You can download the demo page from GitHub.
The page contains the library and the demo pages.
If you want to start at a deeper level, you can check out TensorFlow and dlib.
Face-api uses TensorFlow as a machine Learning library.
Once you have everything downloaded from GitHub, you can use the examples library to explore different methods for face-recognition.
What are the use cases?
In industry, face recognition is used for access control, attendance checks and other security related case.
In social media networks, your face can be tagged so that you can search for your face rather than your name.
For your own system, you can use it for access to your computer and even control some of your applications.
What are we developing?
We are making a simple system to detect a face.
To detect a face, you need to have the software, images and a trained model.
You can train the model yourself and you should but for your specific task, you can also re-train an existing model.
In this example, the model is pre-trained and downloaded.
For the code to work, you need to collect the sample.
In this case we use a webcam, simple enough with HTML5.
To do this, add a video tag in the html code.
<video id = "videoID" autoplay muted></video>
Simple right? but wait you need to call this from your JavaScript also.
const video = document.getElementById('videoID')
Now you can use the constant to get your stream into the JavaScript code.
Create a startVideo function.
function startVideo() {
navigator.mediaDevices.getUserMedia({ video: {} },
stream => video.srcObject = stream,
err => console.error(err))}
This is a general function that does not call the videoID, you need to set a function that calls the incoming stream.
A way to catch the stream is to use Promise functions.
Promise.all([
faceapi.nets.tinyFaceDetector.loadFromUri('/models'),
faceapi.nets.faceLandmark68Net.loadFromUri('/models'),
faceapi.nets.faceRecognitionNet.loadFromUri('/models'),
faceapi.nets.faceExpressionNet.loadFromUri('/models')]).then(startVideo);
The Promise statement above will now run the startVideo function when the stream is available.
Finally, the video event listener below will run the functions available from the face API.
video.addEventListener('play', () => {const canvas = faceapi.createCanvasFromMedia(video);
document.body.append(canvas);const displaySize = { width: video.width, height: video.height };
faceapi.matchDimensions(canvas, displaySize);
setInterval(async () => {const detections = await faceapi.detectAllFaces(video, new
faceapi.TinyFaceDetectorOptions()).withFaceLandmarks().withFaceExpressions();const resizedDetections = faceapi.resizeResults(detections, displaySize);
canvas.getContext('2d').clearRect(0, 0, canvas.width, canvas.height);
faceapi.draw.drawDetections(canvas, resizedDetections);
faceapi.draw.drawFaceLandmarks(canvas, resizedDetections);
faceapi.draw.drawFaceExpressions(canvas, resizedDetections);}, 100);});
What do you need in your development environment?
Since we are using JavaScript, we need nodejs, node and npm (or similar).
your best tactic here is to create your development directory and then clone the repository from GitHub.
The examples are in the examples directory so move there.
$ cd examples/example-browser/
Inside the directory you need to install the packages using npm.
$ npm install
Since you are in the directory where you downloaded face-api.js, npm will find what you need to download.
Next you can start the demo and open it in your browser.
$ npm start
The last line in the output shows the port you need to use in your browser.
These examples are usually of the cast of Big Bang Theory but you can load in your own pictures and even use the webcam to determine your age.
These demos are fun to play with but the real value is that the code is available to study.
In the files, the JavaScript are separated in a separate directory to make it easy to use.
For your pages to work you need to load in the API and all scripts you are going to use.
Conclusion
This is a very short example of how to use existing API’s to detect faces and recognise them.
The really fascinating part is to find useful applications for the technology.
What will you use it for? Access to your own machine or just some specific data or application?
Setting Up Node.js Development Environment
You can always install Node.js on your computer and run Node.js applications there.
But, there are situations where you will want to use Docker to do your Node.js development.
For example, let’s say, you don’t want to install Node.js on your computer and still want to develop Node.js applications or test an existing one.
In that case, you can simply use a Node.js Docker container.
Another example is where you need to test your Node.js application on different versions of Node.js.
In that case, you can use different Node.js Docker containers with different version of Node.js installed to test your application.
In this article, I will show you how to set up Node.js development environment using Docker.
So, let’s get started.
Setting Up Project Directory:
In this section, I will clone one of my Node.js API app from GitHub to my ~/Projects/ directory just for testing Docker Node.js development environment I am about to show you how to setup.
This is not required.
You can always use your own Node.js app if you want.
First, I am going to navigate to my ~/Projects/ directory as follows:
$ cd ~/Projects/
Now, I am going to clone my shovon8/angular-hero-api GitHub repository as follows:
$ git clone https://github.com/shovon8/angular-hero-api
The project files will be in the angular-hero-api/ directory as you can see in the screenshot below.
Node.js Docker Images:
There are official container images for different version of Node.js built on top of different Linux distribution on DockerHub.
Visit https://hub.docker.com/_/node/ from your favorite browser to find the Node.js image you need.
As you can see, the tag name for all the Node.js images are listed in the DockerHub page of Node.js.
You can either use Debian Jessie/Stretch, Alpine, ChakraCore Linux distribution based images for different versions of Node.js.
Usually, you don’t have to know much to use a Node.js Docker image.
If you want to use Node.js version 12, then all you have to do is write node:12 when you make a container.
For Node.js 10, it is node:10.
For Node.js 8, it is node:8.
It’s that simple.
Configuring the Node.js Development Environment:
In this section, I am going to configure Linux command aliases for my Node.js API app.
That way, I can easily use any version of Node.js I want to run my app.
In each of my Node.js project directory, I will create a new file source.
In that file, I will keep the command aliases like node12 for Node.js 12 runtime, node10 for Node.js 10 runtime, node8 for Node.js 8 runtime running on Docker.
You can reuse the same source file with slight modification on your other Node.js projects as well.
First, navigate to your project directory as follows:
$ cd angular-hero-api/
Now, create a source file with the following command:
$ nano source
Now, type in the following lines in the source file.
alias node12='docker run -it --rm --name hero-api -p 4242:4242 -v
"$PWD:/usr/src/app" -w /usr/src/app node:12'alias node10='docker run -it --rm --name hero-api -p 4242:4242 -v
"$PWD:/usr/src/app" -w /usr/src/app node:10'alias node8='docker run -it --rm --name hero-api -p 4242:4242 -v
"$PWD:/usr/src/app" -w /usr/src/app node:8'
Here, -it means, run the container in interactive mode.
–rm means remove the container automatically when it’s no longer needed.
–name hero-api defines a name for the container.
-p 4242:4242 means the container port 4242 is forwarded to the destination port (on your computer) 4242.
The format of this option is -p destination:source.
Remember, the first port before the colon (:) is the destination port.
If you want to access your application on some other port than 4242 on your computer, then you have to change the destination port.
If your applications run on some other port than 4242.
Then you have to change the source port.
NOTE: As I will only be using one of the containers at any one time, the name and destination port can be the same.
If you wish to run or test your Node.js application on multiple Node.js version at the same time, then make sure the name and destination port is different for each of the containers in the source file.
Once you’re done, save the file by pressing <Ctrl> + x followed by y and <Enter>.
Now, enable the aliases with the following command:
$ source source
Now, you can run any version of node runtime whenever you need with node12, node10, node8 commands as you can see in the screenshot below.
Running Hero API Node.js App:
Now, let’s see how to run the angular-hero-api app from my GitHub repository with this setup.
I am going to use Node.js 12 runtime first, then go for Node.js 10 and Node.js 8 runtime to show you that it works in each of the versions.
The API app does not have any node modules installed.
So, you have to install all the required node modules with npm install command as follows:
$ node12 npm install
The node modules are installed as you can see in the screenshot below.
Now, run the Node.js API app as follows:
$ node12 npm run test
As you can see, the API server is running on port 4242 on the container.
I also forwarded the port to 4242 on my computer.
So, I should be able to access it on port 4242.
Yes, I can access it.
It’s working as expected.
Now, stop the container by pressing <Ctrl> + c.
Let’s try to run the API app with Node.js version 10.
$ node10 npm run test
As you can see, it’s running.
It works for Node.js 10 as well.
Finally, let’s try for Node.js version 8.
$ node8 npm run test
The API app is running on Node.js 8 runtime as well.
Perfect! It works correctly.
So, that’s how you set up Node.js development environment using Docker.
Thanks for reading this article.
NodeJS with Redis
Redis is widely used as a caching server.
At times, Redis is used as a database as well.
It stores the data in a computer’s memory (RAM) directly.
The advantage is that it can access the data very fast.
The disadvantage is that the data it stores is temporary.
If you reboot your computer, then all the data will be gone.
In this article, I will show you how to use Redis with Node.js.
I will be using Node.js 10.x on Debian 9 Stretch in this article.
But any modern version of Node.js should work.
So, let’s get started.
To get started you must have the following requirements:
js and NPM installed on your computer.
Redis installed on your computer.
You should be able to find articles on installing Node.js and NPM on your desired Linux distribution on LinuxHint.com.
I’ve written a dedicated article on installing Redis on Ubuntu/Debian.
Starting Redis:
You can check whether redis service is running with the following command:
$ sudo systemctl status redis
As you can see, redis service is running.
If redis service is not running in your case, start it with the following command:
$ sudo systemctl start redis
Initializing the Project Directory:
First, create a project directory (let’s call it node-redis) with the following command:
$ mkdir ~/node-redis
Now navigate to the project directory ~/node-redis
$ cd ~/node-redis
Now create a package.json file:
$ npm init -y
Installing Redis Node.js Module:
There are many Redis clients for Node.js.
The official website of Redis recommends redis.
You can easily install the redis Node.js module using NPM (Node Package Manager).
To install redis Node.js module, run the following NPM command:
$ npm install redis --save
redis Node.js module should be installed.
Connecting to Redis using Node.js:
In this section, I am going to show you how to connect to Redis data store using Node.js.
First, create a new file connect.js in your project directory and type in the following commands in it:
Here, line 1 imports the redis module.
Line 2 creates a Redis client.
As I am running Redis on the same computer as the Node.js programs are running, I didn’t have to specify the hostname or IP address and port where the Redis server is running.
If you’re running Redis server on a different computer or server, then you will have to specify it here.
For example, let’s say, your Redis server is running on port 6379 on a computer which has the IP address 192.168.10.87, then you would write line 2 as:
let client = redis.createClient(6379, '192.168.10.87');
Line 4-6 is used to print a message to the console if we can connect to the Redis server.
Line 9-10 is used to print a message to the console if we are unable to connect to the Redis server.
Now, run the connect.js Node.js script as follows:
$ node connect.js
As you can see, I am connected to the Redis server.
Storing Data in Redis Using Node.js:
In this section, I will show you how to store data (key-value pairs) in Redis data store with Node.js
First, create set1.js file in your project directory and type in the following lines in it:
Here, line 1 and 2 are the same as in connect.js.
On line 4, I set the callback function of the connect event to storeData.
So, when our Redis client is connected to the Redis server, the function storeData is called.
On line 6-10, the callback function storeData is defined.
On line 7 and 8, I used set(key, value) method of RedisClient object to set the key name and country to value Mary Smith and USA respectively.
Now, run set1.js as follows:
$ node set1.js
As you can see, the key-value pairs are set.
Retrieving Data from Redis Using Node.js
In this section, I will show you how to retrieve data from Redis data store using Node.js.
First, create a new file get1.js in your project directory and type in the following lines:
Here, on line 4, getData function is set as a callback function for the connect event of RedisClient.
On line 6-9, the getData function is defined.
On line 7, I called the get(key, callback) method of RedisClient object.
name here is the key of the value you want to retrieve.
get() method calls the printValue callback function before it finishes running.
On line 11-18, the error first style callback function printValue() is defined.
It accepts 2 arguments, error and result.
If any error occurs, then it’s printed on the console and the function exits.
If there’s no error, then the value for the certain key is printed on the console.
On line 8, the same thing happens.
Now, run get1.js as follows:
$ node get1.js
As you can see, the values for the keys name and country is retrieved from the Redis data store.
Storing Objects in Redis with Node.js:
You can store JavaScript objects in Redis data store.
First, create a new file set2.js in your project directory and type in the following lines in it.
Here, everything is the same as in set1.js file that I already explained earlier.
The only difference is, I used client.hmset(key, object) method of RedisClient object in setData() callback function.
In line 7-10, I used client.hmset() method to store a JavaScript object in the Redis data store against the key C011.
Now run set2.js Node.js script as follows:
$ node set2.js
As you can see, the object is stored.
Retrieving Objects from Redis with Node.js:
In this section, I am going to show you how to retrieve objects from Redis data store.
Fist, create a new file get2.js in your project directory and type in the following lines in it.
Here, everything is the same as in get1.js script I explained earlier.
You can retrieve a JavaScript object very easily with client.hgetall(key, callback) method of RedisClient as in line 7-9.
Now run get2.js Node.js script as follows:
$ node get2.js
As you can see, the JavaScript object is retrieved from the Redis data store.
I showed you how to setup Redis with Node.js in this article.
Now you should be able to read the redis Node.js module documentation at http://redis.js.org and learn more about it.
Thanks for reading this article.
Node.js Send E-Mail with Attachment
Node.js is the server side JavaScript engine that is loved by web developers and system administrators all over the world.
Node.js has a rich set of modules that you can install using Node Package Manager (NPM) and use to do almost any task.
There are many Node.js modules for sending E-Mails using Node.js such as Nodemailer, emailjs, express-mailer etc.
In this article, I will show you how to send E-Mail and also how to send E-Mail with attachment with Nodemailer Node.js module.
Let’s get started.
Requirements:
To follow this article, you should have:
Basic understanding of Node.js and JavaScript.
js 6.x or later installed on your computer.
NPM installed on your computer.
An E-Mail account such as GMail.
A Text Editor for writing Node.js codes.
You should be able to find dedicated articles on each of these topics on linuxhint.com.
Be sure to check them for more information.
Creating Project Directory:
It’s always best to create a new directory for every Node.js app you write.
Because by default, Node.js modules are installed in node_modules/ directory inside your current working directory.
That way, modules are separate for each app you write and you can use different version of the same module in different app.
This is a lot flexible than installing modules globally.
Create a project directory (let’s call it node-mail) with the following command:
$ mkdir node-mail
Now navigate to the project directory with the following command:
$ cd node-mail
Now create a package.json file with the following command:
$ npm init -y
As you can see, a basic package.json file is created.
Installing Nodemailer:
In this section, I am going to show you how to install Nodemailer Node.js module using NPM.
First, make sure Node.js is installed and working correctly with the following command:
$ node --version
As you can see, Node.js 10.11.0 is installed and working correctly in my computer.
The version on your computer may be different.
It’s alright but it should be version 6.x or later.
Otherwise Nodemailer won’t work.
Now, make sure NPM is installed and working correctly with the following command:
$ npm ---version
As you can see, NPM 6.4.1 is installed and working correctly in my computer.
The version on your computer may be different.
It’s alright.
You need internet connectivity in order to install Nodemailer using NPM.
So make sure you’re connected to the internet.
Now, install Nodemailer Node.js module using NPM with the following command:
$ npm install nodemailer --save
Nodemailer is installed.
Sending E-Mail with Nodemailer:
In this section, I will show you how to send E-Mail from your gmail account with Nodemailer.
First, create a new file (let’s call it sendmail.js) in your project directory with the following command:
$ touch sendmail.js
Now type in the following lines of code in sendmail.js file and save it.
Here, on line 1, I imported Nodemailer.
On line 3, I set my email to myEmail variable.
This is the email from which I will send an email to other email accounts.
Make sure you change it to your email address.
On line 5-11, a transport object is created.
It is required to send an email using Nodemailer.
The purpose of the transport object is to verify the sender information.
You only need to do it once.
Once the sender information is verified, a transport object should be created.
On line 6, I set service to gmail as I am using a GMail account to send emails.
The supported services are DynectEmail, Gmail, hot.ee, Hotmail, iCloud, mail.ee, Mail.Ru, Mailgun, Mailjet, Mandrill, Postmark, QQ, QQex, SendGrid, SES, Yahoo, yandex, Zoho.
The service name is case insensitive.
So you can put gmail or GMAIL or Gmail there.
It’s all the same.
Make sure you set the correct service name.
NOTE: You can use your own email server as well.
To do that, you have to create a custom Nodemailer Transport object.
To learn more about it, visit the official documentation of Nodemailer at https://nodemailer.com/smtp/
On line 9, I put the password of my gmail account that I am using to send emails from.
Make sure you change it to yours.
On line 14-19, I created a message object.
In this object, from is set to the email address of the sender, to is the email address of the receiver.
subject is the subject of the email and text is the content of the email.
On line 22, I used the transport.sendMail() method to send email using Nodemailer.
The first argument of the sendMail() method is the message object defined on line 14-19.
The second argument is a callback function.
The callback function simply checks for errors and prints a message to the console depending on whether the email was sent or not.
Now run the sendmail.js script as follows:
$ node sendmail.js
As you can see, the email was sent.
I checked my Gmail, and voila! I received the email just fine.
Sending E-Mail with Attachment Using Nodemailer:
Now that you know how to send email using Nodemailer, sending email with attachment is a piece of cake!
To send email with attachment, all you need to do is modify the message object on line 14-19 and the rest of the code should be the same.
Change the message object as follows as save the file.
Here, attachments is an array objects.
Each object defines an attachment file.
So you can send multiple files at once.
On line 20-22, I set the relative path to a file hello.txt to the path property of the object.
Now run the sendmail.js script again.
$ node sendmail.js
As you can see, the email was sent.
As you can see, I received the message along with the attachment hello.txt.
You can also set custom name to your attachment file.
For that, you have to change the attachment object as follows:
To send multiple attachments, create multiple attachment objects as follows:
That’s how you send email with attachment using Nodemailer in Node.js.
Thanks for reading this article.
NodeJS Debugger Tutorial
No matter how good you are at programming NodeJS, there will always be things happening that you don’t want.
So debugging a NodeJS app is very important to find and fix the problems and get the app running as soon as possible.
NodeJS has powerful debugging features build in, which is really helpful.
You can use the NodeJS debugger from the command line very easily.
In this article, I will show you how to use the NodeJS debugger.
I am using NodeJS 8 on Debian 9 Stretch for the demonstration.
But everything shown in this article should work on any latest NodeJS version on any Linux distributions, Mac OS and Windows.
So Let’s get started.
Installing NodeJS:
NodeJS may not be installed on your computer by default.
But it is freely available to download and install.
Just go to the official website of NodeJS at https://nodejs.org/en/ and download NodeJS for your operating system.
It is available for Mac OS, Linux and Windows.
So no matter what operating system you have, you should be able to install it.
Setting Up the Test Program:
The NodeJS program I used in this article is given below:
This is a simple NodeJS program that adds 2 numbers.
You can run the NodeJS script app.js with the following command:
$ node app.js
In the next section, I will show you how to use the NodeJS debugger.
Starting NodeJS Debugger:
To debug the NodeJS script app.js, you have to run the script app.js with the NodeJS debugger.
You can start the NodeJS debugger for app.js the following command:
$ node inspect app.js
NOTE: On older version of NodeJS, you run node debug app.js instead to start the NodeJS debugger.
NodeJS debugger should start as you can see in the screenshot below.
Now you can run many commands here to debug the NodeJS script app.js.
Getting Help with NodeJS Debugger:
You can run the following command to get a list of commands and functions that you can use to debug a NodeJS script in the NodeJS debugger:
debug> help
As you can see, all the commands and functions with short description of what they do are listed.
When you are having a hard time remembering what commands or functions to run, this is a good place to get some help.
Auto Completion on NodeJS Debugger:
You can partially type in a command or function and press <Tab> to get auto completion.
Before pressing <Tab>:
After pressing <Tab>.
As you can see, the function is auto completed.
In the next sections, I will show you how to do different debugging task with NodeJS debugger.
Setting Breakpoints with NodeJS Debugger:
A NodeJS script has many numbered lines when viewed in a programming text editor.
You can set breakpoints on any of these lines.
Let’s say you set a breakpoint on line 3, and start the NodeJS script.
Then the NodeJS debugger would run line 1 and 2 and stop at line 3.
Then you can check whether the results up until this point is correct and continue the program as usual.
You can set as many breakpoints as you need.
To set a breakpoint, you run the setBreakpoint() function.
The function accepts an integer parameter as line number to which you want to set a breakpoint.
setBreakpoint(int lineNumber)
To set a breakpoint on line 3,
Run the following command:
debug> setBreakpoint(3)
As you can see, a breakpoint is set on line 3, which is marked by an arrow (>).
Now let’s set a breakpoint on line 22 as well:
debug> setBreakpoint(22)
As you can see, a breakpoint is set on line 22 as well, just before the first addNumber() function is executed.
Removing or Clearing Breakpoints with NodeJS Debugger:
To remove a breakpoint, just run the clearBreakpoint() function.
clearBreakpoint(int lineNumber)
Pass in the line number at which you have a breakpoint set as an argument to the function clearBreakpoint(), the breakpoint should be removed or cleared.
Listing All the Breakpoints with NodeJS Debugger:
You can list all the breakpoints you have already set with the NodeJS debugger with the following command:
debug> breakpoints
As you can see, I have breakpoints set on line 3 and line 22.
Using REPL in NodeJS Debugger:
The full form of REPL is Read–Eval–Print Loop.
You can use REPL in NodeJS debugger to check the contents of variables and functions and many more.
It is really useful.
To start REPL, run the following command:
debug> repl
As you can see, REPL has started.
Now you can press <Tab> twice to see what variables and functions are available at the moment in your NodeJS script.
You can also print the content of any variable you wish.
Just type in the name of the variable and press <Enter>.
You can also check functions as well.
To exit REPL, press <Ctrl> + c.
You should be back to the debugger.
Using the cont Command in NodeJS Debugger:
Now that you have all the breakpoints set, you can run the cont command or c command to continue running the lines till the first breakpoint.
debug> c
Now I can check the value of x and y from REPL and as you can see it is correct.
To go to the next breakpoint, you can run c command again.
The variables are printed with REPL.
Running the c command again completes the program as there are no more breakpoints.
Resetting Program Execution:
If you want to start executing lines from the beginning of your NodeJS script, you have to reset the debugger.
You can reset the debugger with the following command:
$ r
Debugging NodeJS Script Line By Line:
You can use the next or n command to run a NodeJS script line by line.
At first, I have no value set for x and y.
I executed 1 line:
debug> n
Now x is set to 5 and y is still undefined.
You can move line by line and keep debugging your NodeJS script like this.
Though there are many things I could not cover, but this is the basics of using the NodeJS debugger to debug a NodeJS app.
Now it should be easy to learn more about NodeJS debugger with the help command.
How to Install and Configure NodeJS on CentOS 7
JavaScript is the programming language of the Web.
It is mainly used in Web browser to make your website interactive.
But a web browser is not the only place JavaScript is used these days.
JavaScript can be used just like any other interpreted programming languages such as Python, Ruby etc.
NodeJS made it possible.
NodeJS is basically JavaScript on the server.In this article, I will show you how to install and configure NodeJS on CentOS 7.
Let’s get started.
Installing Build Tools for Native Addons:
All the NodeJS modules are written.
At times that has performance issues as JavaScript is not as fast as a compiled language such as C and C++.
To solve this problem, NodeJS has native addons.
How that work is, NodeJS relies on Chrome V8 JavaScript engine, which is written in C++.
So NodeJS adds an additional layer to compile JavaScript code to native binary code.
This improves performance drastically.
NodeJS codes runs almost as fast as C and C++ compiled code if the NodeJS module that you’re using is written using the Native Addons NodeJS API.
The NodeJS native addons needs a C++ build tool installed on your computer as the modules are built while you install them using Node Package Manager.
I will show you how to install build tools here.
First update the YUM package repository cache with the following command:
$ sudo yum makecache
The YUM package repository cache should be updated.
Now install build tools on your CentOS 7 machine with the following command:
$ sudo yum install gcc-c++ make
Now press y and then press <Enter>.
The build tools should be installed.
Adding NodeJS Package Repository on CentOS 7:
At the time of this writing, you can install either NodeJS 8.x or NodeJS 10.x.
NodeJS 8 is the LTS release and NodeJS 10 is latest release.
Both of these versions are available to install on CentOS 7.
Add the package repository of either NodeJS 8.x or NodeJS 10.x depending on your need.
For NodeJS 8.x:
Run the following command to add the package repository of NodeJS 8.x on your CentOS 7 machine:
$ curl --silent --location https://rpm.nodesource.com/setup_8.x | sudo bash -
For NodeJS 10.x:
Run the following command to add the package repository of NodeJS 10.x on your CentOS 7 machine:
$ curl --silent --location https://rpm.nodesource.com/setup_10.x | sudo bash -
I went for the LTS release of NodeJS, which is version 8.x.
As you can see, the package repository is added.
Installing NodeJS:
Now you can install NodeJS on your CentOS 7 machine with the following command:
$ sudo yum install nodejs
Now press y and then press <Enter> to continue.
Now press y and then press <Enter> to accept the GPG key.
NodeJS should be installed.
Now run the following command to verify whether NodeJS is working:
$ node --version
As you can see, NodeJS is working properly.
Now run the following command to see whether Node Package Manager (NPM) is working:
$ npm --version
As you can see, NPM is working correctly as well.
Using NodeJS:
Now that you have NodeJS installed, I am going to show you the basics of NodeJS.
First create a project directory with the following command:
$ mkdir hello-world
Now navigate to the project directory:
$ cd hello-world/
Inside hello-world/ directory, initialize a Node package.json file with the following command:
$ npm init -y
As you can see a package.json file is generated.
The contents of the file are also printed on the terminal.
It is a JSON file.
Here, name is the application name, version is the application version, description is a short description about your application, main is the name of a NodeJS script in your project directory that is used to start your application.
By default, it is index.js, but you can change it.
scripts is an object that holds command aliases.
I am going to leave the defaults for now.
Now install Express.js NodeJS package with NPM with the following command:
$ sudo npm install express --save
Express should be installed.
All the modules are kept in the node_modules/ directory in your project directory.
Now create a index.js file and type in the following codes:
let express = require('express');
let app = express();
app.get('/', (req, res) => {
res.end('<h1>Welcome to LinuxHint</h1>');});
app.listen(8080, () => {
console.log('App is running on http://localhost:8080');});
Now run the following command to start the app:
$ node index.js
The app should start.
Now from your web browser, go to http://localhost:8080 and you should see the following output.
The NodeJS app is working correctly.
Now to stop the app, press <Ctrl> + c on the terminal.
Now if you visit http://localhost:8080 from the web browser, you should see an error.
That’s how you install and configure NodeJS on CentOS 7.
How to Install and Use NPM on Debian 9 Stretch
NPM or Node Package Manager is the same thing as APT to Debian.
It is used to install, remove, update NodeJS packages.
In this article, I will show you how to install and use NPM on Debian 9 Stretch.
Installing NodeJS and NPM
The version of NodeJS available in the official Debian 9 Stretch package repository is 4.x, which is very old.
The official package repository of Debian 9 Stretch does not have NPM.
In this section, I will install the latest stable version of NodeJS and NPM which is at the time of this writing 8.11.1.
First update the apt package repository cache with the following command:
$ sudo apt-get update
Now install CURL with the following command:
$ sudo apt-get install curl
Press y and then press <Enter> to continue.
CURL should be installed.
Now add the package repository of NodeJS 8.x with the following command:
$ curl -sL https://deb.nodesource.com/setup_8.x | sudo -E bash -
The NodeJS 8.x package repository should be added as you can see from the screenshot below.
Now you can install NodeJS and NPM all together along with the development tools for building native NodeJS modules with the following command:
$ sudo apt-get install build-essential nodejs
Now press y and then press <Enter> to continue.
NodeJS, NPM and the required build tools for compiling NodeJS native modules are installed.
Now check whether NodeJS is working with the following command:
$ node --version
As you can see, NodeJS 8.11.1 is installed and working correctly.
Now check whether NPM is working with the following command:
$ npm --version
As you can see NPM is installed correctly as well.
Using NPM
In this section, I will show you how to use NPM to manager NodeJS modules or packages.
Before that, let’s talk about global packages and local packages.
If you install a NodeJS package globally, then it should be saved somewhere /usr/lib/node_modules directory and you can access it from any NodeJS project.
If you install a NodeJS package locally, then a directory node_modules/ should be created on your project directory and the package should be saved in node_modules/ directory relative to your project directory.
It can only be accessed from that project.
That’s all you need to know for now.
Let’s continue.
Creating a package.json Configuration File with NPM:
Every NodeJS project has a package.json file in its project’s root directory.
This file holds information about your project, such as the name of the project, the version of the project, the dependencies or other NodeJS packages your project depends on and many more.
You can manually create a package.json file and put all these information or you can use NPM to create it for you.
First create a new directory node-project (you can name is whatever you want) for your NodeJS project with the following command:
$ mkdir node-project
Now navigate to your project directory with the following command:
$ cd node-project
Now to create a package.json file with NPM, run the following command:
$ npm init
Fill in the details and press <Enter> to move forward.
In the end, type in yes and press <Enter>.
As you can see, a package.json file is created.
This is the contents of the package.json file:
Installing a NodeJS Package Locally with NPM:
If you know the name of the package, then you can easily install it using NPM.
For example, if you want to install express NodeJS package, which is Express web framework, run the following command from your project directory:
$ npm install express --save
express NodeJS package should be installed.
Installing a NodeJS Package Globally with NPM:
You can install a NodeJS package globally from any directory.
For example, if you want to install express NodeJS package globally, run the following command:
$ sudo npm -g install express
It should be installed globally.
Removing a NodeJS Package Locally with NPM:
If you want to remove a NodeJS package, let’s say express, from your project directory, run the following command from your project directory:
$ npm uninstall express --save
The express NodeJS package is removed.
Removing a NodeJS Package Globally with NPM:
To remove a NodeJS package, let’s say express, globally, run the following command:
$ sudo npm -g uninstall express
It should be removed.
Searching for NodeJS Packages:
Well, now you know how to install and remove NodeJS packages with NPM.
Now the question is, how do I know what I can install with NPM? What packages are available?
Well, you can search for packages in the NPM’s official website at https://www.npmjs.com/ or you can use NPM command line utility.
To search for NodeJS packages from your web browser, go to https://www.npmjs.com/ and search for what you’re looking for.
Type in the keywords as marked in the screenshot below, and press <Enter>.
You should see a lot of packages as you can see in the marked section of the screenshot below.
You can click on any one of them to see more information about that package.
You can also run the following command to search for NPM packages:
$ npm search "Web framework"
As you can see, the same list is displayed.
You can pick up the package name from the first column as marked in the screenshot below, and install what you need using NPM.
So that’s how you install and use NPM on Debian 9 Stretch.
Thanks for reading this article.
Creating Charts using JavaScript and PHP
Web based chart can be created by using any client-side library or server-side library based on static or dynamic data.
If you want to create animated charts and want to download the chart faster then it is better to use a client-side chart library.
Many client-side libraries are available to create charts for web pages.
One of the popular client-side libraries is CanvasJS which can be used to create web based charts by using fixed data or retrieving data from any database.
CanvasJS is used with PHP in this tutorial for creating web based charts.
This library supports various types of charts, such as bar chart, column chart, dynamic column chart, line chart, pie chart, pyramid chart, doughnut chart, bubble chart etc.
Some of them are shown here by using sample data.
Before starting this tutorial, you must ensure that your web server and PHP are installed properly and working.
Download CanvasJS
It is available in free and commercial version.
You can download and use the free version of this library for testing purposes.
Go to the following URL and click on Download link to download CanvasJS library.
Unzip the file and store the folder in web server after download to use it.
https://canvasjs.com
<?php
$profitdata = array(
array("x"=> 2013, "y"=> 440000),
array("x"=> 2014, "y"=> 270000),
array("x"=> 2015, "y"=> 210000, "indexLabel"=> "Lowest"),
array("x"=> 2016, "y"=> 600000),
array("x"=> 2017, "y"=> 630000, "indexLabel"=> "Highest"),
array("x"=> 2018, "y"=> 560000) );
?>
<html><head><script src="http://localhost/canvasjs/canvasjs.min.js"></script><script>
window.onload = function () {
var chart = new CanvasJS.Chart("displaychart", {//Enable animation
animationEnabled: true,
//To save the chart as image
exportEnabled: true,
//The others values of theme are "light1", "light2", "dark1"
theme: "dark2",
title:{
text: "Yearly Profits"},
data: [{//Change type to bar, line, pie etc.
to change the display
type: "column",
indexLabelFontColor: "#5A3457",
indexLabelPlacement: "outside",//Read data from PHP array in JSON format
dataPoints: <?php echo json_encode($profitdata, JSON_NUMERIC_CHECK); ?>}]});
chart.render();
}</script></head><body><center><h3>Column Chart Example </h3><div id="displaychart" style="height: 70%; width: 40%; align:center;"></div></center></body></html>
Output:
The following output will be generated if you run the file from any web server.
“Trial Version“ and “CanvasJS.com” watermarks will be shown for free version.
When you click on “More Options” button from top right corner then three options will be shown.
You can print the chart or save the chart as JPG or PNG image format.
If you click on “Save as PNG” option then the following dialog box will appear.
The default image file name is Chart.png. You can remove the watermarks from the image by using any photo editing software easily.
Pie Chart:
The following example shows the popularity of different Linux distributions using pie chart.
Write the following code in a file named pie-chart.php and store the file in var/www/html/jschart folder.
<?php
$popularity = array(
array("os"=> "Arch Linux", "y"=> 40),
array("os"=> "CentOS", "y"=> 25),
array("os"=> "Debian", "y"=> 12),
array("os"=> "Fedora", "y"=> 10),
array("os"=> "Gentoo", "y"=> 8),
array("os"=> "Lindows", "y"=> 5));
?>
<html><head><script src="http://localhost/canvasjs/canvasjs.min.js"></script><script>
window.onload = function () {
var chart = new CanvasJS.Chart("displaychart", {//Enable animation
animationEnabled: true,//To save the chart as image
exportEnabled: true,//The others values of theme are "light1","dark1", "dark2"
theme: "dark1",
title:{
text: "Popularity of Linux Distributions"},
data: [{//Change type to bar, line, column etc.
to change the display
type: "pie",//Set font color for the label
indexLabelFontColor: "yellow",//format the percentage values
yValueFormatString: "##0.00'%'",//Set angle for pie
startAngle: 240,
indexLabel: "{os} {y}",//Read data from PHP array in JSON format
dataPoints: <?php echo json_encode($popularity, JSON_NUMERIC_CHECK); ?>}]});
chart.render();
}</script></head><body><center><h3>Pie Chart Example </h3><div id="displaychart" style="height: 70%; width: 40%;"></div></center></body></html>
Output:
The following output will display if you run the file from web server.
You can create image file of the chart by the step which is shown in the previous example.
Dynamic Column Chart:
You can create nice looking dynamic chart by using this library.
Suppose, you want to create live chart of stock market where stock price increases or decreases continuously.
Write the following code in a file named dynamic-chart.php and store the file in var/www/html/jschart folder.
<?php
$stockdata = array(
array("stock"=> "MSFT", "y"=> 92.67),
array("stock"=> "LOW", "y"=> 88.89),
array("stock"=> "INTC", "y"=> 52.15),
array("stock"=> "ADI", "y"=> 91.78),
array("stock"=> "ADBE", "y"=> 224.80),
array("stock"=> "ABBV", "y"=> 94.30),
array("stock"=> "AMD", "y"=> 10.27)
);
?>
<html><head><script src="http://localhost/canvasjs/canvasjs.min.js"></script><script>
window.onload = function () {
var chart = new CanvasJS.Chart("displaychart", {//Enable animation
animationEnabled: true,//To save the chart as image
exportEnabled: true,//The others values of theme are "light1","dark1", "dark2"
theme: "dark1",
title:{
text: "Stock Market Values"},
data: [{//Change type to bar, line, column etc.
to change the display
type: "column",//Set font color for the label
indexLabelFontColor: "red",//format the percentage values
yValueFormatString: "##0.00'%'",
indexLabel: "{y}",//Read data from PHP array in JSON format
dataPoints: <?php echo json_encode($stockdata, JSON_NUMERIC_CHECK); ?>}]});
//Read stock names
var stdata = chart.options.data[0].dataPoints;
var st = new Array();for (var i = 0; i < stdata.length; i++) {
st[i]= stdata[i].stock;}
function updateChart() {
var stockColor, deltaY, yVal, xVal;
var dps = chart.options.data[0].dataPoints;for (var i = 0; i < dps.length; i++) {
deltaY = Math.round(2 + Math.random() *(-2-2));
yVal = deltaY + dps[i].y > 0 ? dps[i].y + deltaY : 0;
xVal = dps[i].stock;
stockColor = yVal > 200 ? "#FF2500" : yVal >= 170 ? "#FF6000" : yVal < 170 ? "#6B8E23 ":null;
dps[i] = {label: st[i], y: yVal, color: stockColor};}
chart.options.data[0].dataPoints = dps;
chart.render();};
updateChart();
setInterval(function() {updateChart()}, 500);}</script></head><body><center><h3>Dynamic Chart Example </h3><div id="displaychart" style="height: 70%; width: 40%;"></div></center></body></html>
Output:
The following output will display if you run the file from web server.
You can create image file of the chart by similar way which is shown in the first example.
By following above steps, you can easily create necessary web based animated charts using this useful JavaScript library.
Creating Charts using JavaScript and PHP
Node Package Manager, or npm, gets installed along with Node.js and you can use it to import software packages built on top of Node.js.
If you are not familiar with the idea of nodejs, it is based off of Google Chrome’s JavaScript engine and can be used for server side scripting using JavaScript.
It brings JavaScript (which traditionally runs on the client e.g a web browser) at the same footing as any other server side language like .NET or php.
Because the language is already very popular and easy to use.
There are now a myriad of applications built on top of the Node.js to the point that it almost has its own ecosystem of applications and frameworks to build applications each bundled as its own package.
The problem with that arises when developers start to improve upon their packages and releases new version.
Like most package managers, npm installs the most recent (stable) release of a package.
So if you install a particular version of Express for your web application and a few years later after a new version of Express, chances are somethings in your app might break in a direct or indirect way.
To circumvent this issue, it is handy to use npm in a way that makes use of version numbers to keep track of packages.
Installing Node.js and npm
If you don’t already have Node.js installed in your system it is a good idea to start with the official LTS release.
The official repository of Ubuntu 16.04 is a bit behind from the latest stable release and we would thus add the Node.js official repo as a PPA.
$curl -sL https://deb.nodesource.com/setup_8.x | sudo -E bash -
The above command fetches a shell script from deb.nodesource.com and runs it via bash.
The script automatically adds the public keys of the repo and updates the source lists for apt package manager.
After this installing Node.js and npm is as easy as running:
$apt install nodejs
Now before we get started with installing and updating various packages, let’s make sure that the version of npm and Node.js is what we desire them to be.
$nodejs --version
$npm --version
The version of npm is not the latest stable release (although we made sure that Node.js is the LTS version)
To update npm itself you can run the command:
$sudo npm install npm@latest -g
Where the -g flag makes sure that the package is installed globally, that is, for all the users.
You can only do this if you are the root user or have root previleges of the system.
After which you can see that the version number for npm has changed.
If you would like to go back you can enter the previous version number in a similar fashion.
For example:
$sudo npm install npm@5.6.0 -g
Installing and updating local packages
npm offers 2 different methods for installing packages.
First is locally to be used in, say, another software that you are trying to build and the second method for installing it is to do it across the system for all users.
This is great if you are trying to install a system utility, say with a CLI interface, to be used as a basic command or a standalone software.
The local packages are directory specific.
For example, if you are building a Node.js app first make project folder or directory:
$mkdir myapp$cd myapp
Now, from inside the directory you can run an npm init command and enter appropriate values for the name, description, git repository and other relevant fields which are the metadata of the package.
Now if you install a package, such as lodash by running the following command in the directory:
$npm install lodash
npm automatically gets the latest stable release of the said package and installs it for you.
If you want to check the version number then, enter the command:
$npm list
If a new version of lodash comes along and you wish to upgrade then, in the same directory, run:
$npm update
Now you can see that the version number is greater than what it was before.
If something is wrong with the new version and you are facing issues, then you can always go back to previous state by simply running.
$npm install lodash@4.17.0
Of course, that would require keeping track of the previous version number.
Performing a git commit before any of the npm update actions is advisable for this reason.
Installing and updating global packages
Installing packages globally is actually much simpler since these are usually standalone utility.
A great example of such a package is gtop which is similar to the top utility in Linux.
It shows all the resource utilization in a clean and elegant way.
To install a package globally, either be the root user or prefix your command with sudo if you are a user with root previleges.
$sudo npm install gtop -g
Now, like any command utility, you can call upon gtop by running:
$gtop
To exit simple hit q and you will fall back to the terminal.
Because there are too many dependencies for gtop simply running npm list -g won’t help us know the verison of gtop.
So we can try this instead:
$npm list gtop -g
If you want to update the package,then simply run:
$sudo npm update gtop -g
And you are done!
Conclusion
So that’s basic package management if you want to use npm packages for your new software project or as a standalone system utility.
If you wish to explore npm packages you can always do so by going to their official website.
Using PostgreSQL from Node.js
PostgreSQL is a very popular open source database.
It is widely used for almost all types of applications.
Node.js has very good modules to work with PostgreSQL database.
In this article, I am going to show you how to connect to a PostgreSQL database from Node.js.
I will use a Node.js module called ‘node-postgres’ to integrate Node.js and PostgreSQL.
Let’s get started.
Pre-requisites:
First you have to make sure that Node.js, NPM and PostgreSQL are installed and running.
You can install and configure PostgreSQL from How to Install PostgreSQL on Ubuntu Linux: The Easy Way and Node.js and NPM from How to install NPM if you don’t have them installed already.
Now check whether Node.js is working with the following command:
$ node --version
Now check whether NPM is working with the following command:
$ npm --version
Now check whether PostgreSQL is working with the following command:
Now create a directory ‘postgre-node’.
Then navigate to the directory you just created with the following command:
$ cd Documents/postgre-node
Then you should run the following command to create a ‘package.json’ file.
$ npm init -y
You can see from the screenshot below that a ‘package.json’ file is created.
Now install ‘node-postgres’ Node.js module using NPM with the following command.
If you remember, ‘node-postgres’ is a PostgreSQL Client for Node.js.
$ npm install --save pg
‘node-postgres’ should be installed.
Using ‘node-postgres’ PostgreSQL Node.js Client:
Now inside the directory ‘postgres-node ’, create a new file ‘index.js ’ and write the following codes as shown in the screenshot below.
const pg = require(‘pg’);
const pool = new pg.Pool({
user: ‘sysadmin’,
host: ‘127.0.0.1’,
database: ‘mywebstore’,
password: ‘123’,
port: ‘5432’});
pool.query(“SELECT NOW()”, (err, res) => {
console.log(err, res);
pool.end();
});
Here const pg = require(‘pg’) imports ‘node-postgres ’ Node.js module.
Then I created a Pool using pg.Pool with PostgreSQL login credentials.
I didn’t change anything from the article for setting up PostgreSQL in the “Pre-requisites” section.
You may take a look at it again.
I simply retrieved the current date and time using the PostgreSQL NOW() function using pool.query() method of ‘node-postgres ’.
I ran SQL statements “SELECT NOW() ”.
Now if I save the ‘index.js’ file and run the Node.js source file with the following command:
$ node index.js
You should see current TIMESTAMP on the output as shown in the screenshot below.
Creating a Table:
Now I am going to create a new Table ‘users’ using the following query:
# CREATE TABLE users(id SERIAL PRIMARY KEY, firstName VARCHAR(40) NOT NULL,
lastName VARCHAR(40) NOT NULL)
The ‘users’ table has 3 fields, id, firstName and lastName.
id is an integer and firstName and lastName fields are strings.
The source code is given on the screenshot given below.
const pg = require(‘pg’);
const pool = new pg.Pool({
user: ‘sysadmin’,
host: ‘127.0.0.1’,
database: ‘mywebstore’,
password: ‘123’,
port: ‘5432’});
pool.query(“CREATE TABLE users(id SERIAL PRIMARY KEY, firstname VARCHAR(40) NOT NULL,
lastName VARCHAR(40) NOT NULL)”, (err, res) => {
console.log(err, res);
pool.end();
});
Now if I run the code, you should see the following output.
Now let’s login to the ‘mywebstore’ datastore as ‘sysadmin’ user with the following command:
$ psql -U sysadmin -h127.0.0.1 mywebstore
It should ask you for the ‘mywebstore’ datastore’s password.
Type in the password and press <Enter>
You should be logged into the PostgreSQL console as shown in the screen below.
Now run the following command to see all the tables:
mywebstore=> \dt
You should see ‘users’ table as shown in the screenshot.
You can run the following command to quit PostgreSQL command line interface:
mywebstore=> \q
Inserting into Table:
Now you can insert into the ‘users’ table with the following command:
# INSERT INTO users(id, firstName, lastName) VALUES(1, ‘Shahriar’, ‘Shovon’)
The source code is given in the screenshot below.
Now if you run the source code, you should see the following output.
Now you can login to the PostgreSQL command line interface with the following command like before:
$ psql -U sysadmin -h127.0.0.1 mywebstore
Run the following SQL query:
$ SELECT * FROM users;
You should see the data you inserted as shown in the screenshot below.
Retrieving Data from PostgreSQL:
You simply execute the following SQL statement to retrieve the data:
# SELECT * FROM users;
The other steps are similar.
So I am not going to explain them again as it is out of scope of this article.
Updating data:
To update an existing row of PostgreSQL’s users table, run the following SQL query:
# UPDATE users SET firstName=’Shovon’, lastName=’Shahriar’ WHERE id=1
Here ‘id ’ is the primary key which is unique to each column of the users table.
After you run this code, firstName and lastName should be updated as shown in the screenshot below.
Deleting a Column from PostgreSQL:
You can run the following SQL statement to delete a column from the PostgreSQL.
# DELETE FROM users WHERE id=1
Here id is the primary key of the users table.
Once you login to the PostgreSQL command line interface, you should not find the row you just deleted.
In this case, I have an empty table.
Because I had only 1 row in the users table.
That’s how you perform CRUD operation with PostgreSQL using Node.js, and thanks for reading this article.
Get started with NodeJS on Ubuntu
NodeJS is an open-source server side framework built on JavaScript under MIT (Massachusetts Institute of Technology) license.
It is mainly used for asynchronous programming and it is a very light weight framework that makes it faster than other frameworks.
It is also supported by most of the popular operating systems.
Different types of applications like web application, command line application, RESTful API etc.
can be developed with this framework.
How you can easily install and use this framework on Ubuntu are shown in this article.
NodeJS Installation Steps
1.Press Ctrl+Alt+T to open the terminal and run the following command to install NodeJS
$ sudo apt-get install -y nodejs
After completing the installation process, type the following command to check the version of the installed framework.
$ nodejs -v
2.To install necessary modules and packages you will need to install NodeJS package manager called npm.
Run the following commands to install the npm.
$ sudo npm install npm –global
Check the version of npm.
$ npm -v
Now, NodeJS is ready to use for developing any application.
How you can apply NodeJS as a beginner is shown in the next part of this article.
Using NodeJS
You can use NodeJS for various types of application development.
As a beginner, how you can create a simple console application and a web server are shown in this part.
Creating Console application
Run the following commands to create a directory named nodejsapp for keeping your code organized, go to the newly created directory and open the nano editor for creating a JavaScript file named firstapp.js.
$ mkdir nodejsapp
$ cd nodejsapp
$ nano firstapp.js
Write the following code in the file to print a output in the console.
Press Ctrl+x and then y to save the file and exit from the editor.
console.log('First NodeJS Application');
Run the following command to execute the code of the firstapp.js file.
$ nodejs firstapp.js
if you get any permission problem to execute the script then you have to run the following command for setting execution permission of firstapp.js file and again run the above command.
$ chmod +x firstapp.js
Creating Local Web Server
JavaScript is a popular client side scripting language which doesn’t require any web server to run.
Web server is required to run any server side scripting language like php, asp etc.
and you need to install a particular web server to run server side scripts.
Using NodeJS framework, you can easily implement a local web server which can be used to run server side script.
Open nano editor to create a new JavaScript file named server.js that will be used to create a local web server.
$ nano server.js
Add the following code in the file to create the server connection on port number 6060.
According to this code, NodeJS will listen for server connection at localhost:6060 and if the connection can be established successfully then 200 code will be generated and ‘NodeJS App’ will be shown as output.
var http = require('http');
var server = http.createServer(function(request response) {
resquest.writeHead(200,{'Content-Type': 'text/plain'});
response.end('NodeJS App');});
server.listen(6060);
console.log('Server is running at http://localhost:6060/');
Save the file by pressing Ctrl+x and y.
Now, execute the following command to run the web server.
If the code executes properly then the message ‘Server is running at http://localhost:6060’ will be displayed in the console.
$ nodejs server.js
Open any browser to check the web server code is working properly or not.
The script will return ‘NodeJS App’as content in the browser if the above code executes properly.
Type the following URL in the address bar for checking.
http://localhost:6060
In the above example, a simple static text is displayed in the browser which is added as the content with response.
But generally, any index file displays when the base URL executes.
So, how you can attach any html file in the server connection script is shown in the next part.
At first, create a very simple html file named index.html using Text Editor with the following code and save it in the nodejsapp directory which is created previously.
<html><body>
<center>
<h2>Testing NodeJS Application </h2>
<p> This is my first web application using NodeJS </p>
</center></body></html>
Now, create another JavaScript file named server2.js with the following code to view index.html file, after creating web server connection.
Here, fs module is used to read the index.html file.
Three types of outputs can be generated based on the code.
If the connection establishes properly and index.html file exists then it will load the content of index.html file in the browser.
If the connection establishes but index.html file does not exist on the current location then ‘Page is not found’ message will print.
If the connection establishes and index.html file also exists but requested url is not correct then ‘Default content’ text will display as by default content.
Port number 5000 is set as listening port here.
So when web server connection establishes successfully then the message ‘Server is listening on 5000’ will show in the console.
var http = require('http');
var fs = require('fs');
var server = http.createServer(function (request, response) {
if (request.url === "/") {
fs.readFile("index.html", function (error, pgResp) {
if (error) {
response.writeHead(404);
response.write('Page is not found');
} else {
response.writeHead(200, { 'Content-Type': 'text/html' });
response.write(pgResp);
}
response.end();
});
} else {
response.writeHead(200, { 'Content-Type': 'text/html' });
response.write('<h1>Default Content</h1>');
response.end();
}});
server.listen(5000);
console.log('Server is listening on 5000');
Save the file and exit from the editor.
Run the server by executing the following command.
$ nodejs server2.js
Type the following URL to view the content of index.html file in the browser.
http://localhost:5000
Now, insert an invalid URL in the browser and check the output.
http://localhost:5000/test
Now modify server2.js file and set the file name as index2.html that does not exit and restart the server.
Type the base URL again to check the output.
NodeJS is a demanding framework and you can perform many tasks using it.
|